4thSpace
4thSpace

Reputation: 44332

How to bind XML file to List<MyClass>?

I've been using the answer here binding xml elements to model in MVC4 to bind an XML file to a model.

This works fine when the XML file has one element. I need to handle the case when there are many elements. I'd like all of those elements to go into a List.

Here's an example file:

<root>
<item>
<firstname>Tom</firstname>
</lastname>Jones</lastname>
<item>
<item>
<firstname>Jane</firstname>
</lastname>Doe</lastname>
</item>
</root>

MyXMLElements class looks like:

[Serializable]
[XmlRoot("item")]
public class MyXMLElements
{
  public string first name {get;set;}
  public string lastname {get;set;}
}

How I do I create a List<MyXMLElements>?

Upvotes: 1

Views: 1419

Answers (4)

Victor Mukherjee
Victor Mukherjee

Reputation: 11025

A solution is given below:

The class should look like this:

[Serializable]
[XmlType(TypeName = "item")]
public class MyXMLElements
{
  public string firstname {get;set;}
  public string lastname {get;set;}
}

The deserialization code is below:

 using (var rdr = System.Xml.XmlReader.Create(@"input.xml"))
            {
                var root=new System.Xml.Serialization.XmlRootAttribute("root");
                var ser = new System.Xml.Serialization.XmlSerializer(typeof(List<MyXMLElements>),root);
                var list=(List<MyXMLElements>)ser.Deserialize(rdr);
            }

Upvotes: 0

Shiva Saurabh
Shiva Saurabh

Reputation: 1289

I think the easiest way is to use the XmlSerializer:

XmlSerializer serializer = new XmlSerializer(typeof(List<MyClass>));

using(FileStream stream = File.OpenWrite("filename"))
{
    List<MyClass> list = new List<MyClass>();
    serializer.Serialize(stream, list);
}

using(FileStream stream = File.OpenRead("filename"))
{
    List<MyClass> dezerializedList = (List<MyClass>)serializer.Deserialize(stream);
}

Upvotes: 2

Neel
Neel

Reputation: 11741

XElement xelement = XElement.Load("..\\..\\XML.xml");
IEnumerable<XElement> employees = xelement.Elements();
Console.WriteLine("List of all Employee Names :");
foreach (var employee in employees)
{
    Console.WriteLine(employee.Element("firstname").Value + employee.Element("lastname").Value );
}

Upvotes: 0

Szymon
Szymon

Reputation: 43023

You can achieve it this way (I'm reading XML from a file, but you can get it from other source):

XDocument xDoc = XDocument.Load(@"C:\new.xml");
List<MyXMLElements> list = (from xEle in xDoc.Descendants("item")
    select new MyXMLElements() { firstname = xEle.Element("firstname").Value, lastname = xEle.Element("lastname").Value }).ToList();

You don't need XmlRoot in this case.

Upvotes: 1

Related Questions