4

I'm looking to bind XML to Model in C# MVC app.

XML:

<people>  
    <person>
        <name>Mr Brown</name>
        <age>40</age>
        <hobby>
            <title>Eating</title>
            <description>eats a lot</description>
        </hobby>
        <hobby>
            <title>Sleeping</title>
            <description>sleeps a lot</description>
        </hobby>
    </person>
    <person>
        <name>Mr White</name>
        <age>40</age>
        <hobby>
            <title>Skiing</title>
            <description>more details on this</description>
        </hobby>
        <hobby>
            <title>Football</title>
            <description>watches football</description>
        </hobby>
    </person>
</people>

Model:

public class People
{
    public string Name { get; set; }
    public string Age { get; set; }
    public IList<Hobbies> Hobby {get; set; }
}
public class Hobbies
{
    public string Title { get; set; }
    public string Description { get; set; }
}

Broken Binding:

var person = from a in xml.Descendants("person")
select new People 
{
    Name = a.Element("name").Value,
    Age = a.Element("age").Value,
    Hobby = *WHAT GOES HERE?*
}

I'n new to C# and looking for the best way to bind the data from the XML to the person var. Which I'll later loop over and output in an HTML table.

Any help would be great.

1
  • can you change xml structure? if yes just put your <hobby> tag to container i.e <hobbies> and then deserialize it Commented Sep 12, 2014 at 12:16

3 Answers 3

4

You have to do it this way:

var person = from a in xml.Descendants("person")
              select new People 
              {
                Name = a.Element("name").Value,
                Age = a.Element("age").Value,
                Hobby = a.Descendants("hobby")
                          .Select(x=> new Hobbies
                                       {
                                         Title =x.Element("title").Value,
                                         Description = x.Element("description").Value
                                       }).ToList()
               };

WORKING FIDDLE:

https://dotnetfiddle.net/2uKdd5

Sign up to request clarification or add additional context in comments.

Comments

1

Looks like you want standard XML deserialization. Some good answers on the best way to do that here

Comments

1

I would use XmlSerializer to load from Xml and to save to xml. You can derive People from this class for example (SerializeManagement) :

public class SerializeManagement<T>
{
    public static T ReadFromXML(string iPath)
     {
        T val = default(T);
        try
        {
            // load from XML
            using (var sw = new StreamReader(iPath, Encoding.Default))
            {
                var ser = new XmlSerializer(typeof(T));
                val = (T)ser.Deserialize(sw);
            }
        }
        catch
        {
            Console.WriteLine("Problem reading from xml data file.");
        }

        return val;
    }

    public void SaveToXML(string iPath)

    {
        try
        {
            //TODO => using
            var sw = new StreamWriter(iPath, false, Encoding.Default);
            var ser = new XmlSerializer(typeof(T));
            ser.Serialize(sw, this);
            sw.Close();
        }
        catch
        {
            Console.WriteLine("Problem saving to xml data file.");
        }
    }
}

If you encounter problems, this could be because of your model definition or xml structure :

Then you can :

1) Generate c# class from the xml using xsd utility;

2) Generate XML from existing class using SaveToXML. That way you are sure the XML structure is compliant with your model.

Enjoy !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.