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

2
  • 1
    Use List<xmlvalues> + XML serialization Commented Jun 30, 2015 at 9:49
  • U could use a simple loop and LINQ to XML to do this Commented Jun 30, 2015 at 9:50

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

5 Comments

A minor correction: lvl.Attribute should be lvl.GetElement(). Otherwise, this answer is a winner.
@MikeHofer Thanx, it would be lvl.GetElement() instead of lvl.Attribute
Saw that, and already corrected the comment. :) Still gave you the up vote.
Edited.. have a check
Thanks. I've given this a try but I get an exception while it's running say that there are multiple root elements.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.