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?
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();
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.