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.

tereško
  • 58,060
  • 25
  • 98
  • 150
I_LIKE_FOO
  • 2,744
  • 3
  • 16
  • 18
  • can you change `xml` structure? if yes just put your `` `tag` to container i.e `` and then deserialize it – Harry89pl Sep 12 '14 at 12:16

3 Answers3

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

adiga
  • 34,372
  • 9
  • 61
  • 83
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
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 !

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
Hellin
  • 62
  • 8
1

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

Community
  • 1
  • 1
Craig
  • 474
  • 7
  • 21