Reputation: 423
public class xmlvalues
{
public int id { get; set; }
public string a { get; set; }
public string b { get; set; }
public string c { get; set; }
}
-- XML Example
<instance>
<id>>1</id>
<a>value 1A</a>
<b>value 1B</b>
<c>value 1C</c>
</instance>
<instance>
<id>>2</id>
<a>value 2A</a>
<b>value 2B</b>
<c>value 2C</c>
</instance>
Using the above example is possible to create an object for each "instance" node in the XML file? In this example there would be 2 instances of the object "xmlvalues" but in theory there could be many more. Is there an easy way to do this?
Upvotes: 0
Views: 284
Reputation: 3019
using list
using System.Xml.Linq;
XDocument xdoc = XDocument.Load(@"...\path\document.xml");
List<xmlvalues> lists = (from lv1 in xdoc.Descendants("instance")
select new xmlvalues
{
id = lv1.Element("id"),
a= lv1.Element("a"),
b= lv1.Element("b"),
c= lv1.Element("c")
}).ToList();
Upvotes: 2
Reputation: 677
One way to do it, you would have to adapt your xpath:
using System.Xml.XPath;
using System.Xml.Linq;
foreach (XElement el in xdoc.Root.XPathSelectElements ( "instance" ) ) {
//do something with el
}
This is faster than .Descendants() because it doesn't have to check all the nodes, just the ones found at the x-path ("instance" in the above case)
Upvotes: 0