1

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>?

Community
  • 1
  • 1
4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • Please include the code attempting to do what you're trying to achieve (even though it certainly won't compile as well...). This isn't the behavior of any built in BCL class that I know of so hopefully you've identified something else to help. – M.Babcock Nov 27 '13 at 05:39

4 Answers4

2

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);
}
Shiva Saurabh
  • 1,281
  • 2
  • 25
  • 47
1

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.

Szymon
  • 42,577
  • 16
  • 96
  • 114
0
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 );
}
Neel
  • 11,625
  • 3
  • 43
  • 61
0

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);
            }
Victor Mukherjee
  • 10,487
  • 16
  • 54
  • 97