Willy
Willy

Reputation: 10648

Read XML document with LINQ TO XML

I have a little XML placed into a string, called myContent:

 <People xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <Person ID="1" name="name1" />
     <Person ID="2" name="name2" />
     (....)
     <Person ID="13" name="name13" />
     <Person ID="14" name="name14" />
 </People>

and in C# I have stored previous XML content in the string variable like below:

        private string myContent = String.Empty +
        "<People xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
        "<Person ID=\"1\" name=\"name1\" />" +
        "<Person ID=\"2\" name=\"name2\" />" +
        (...)
        "<Person ID=\"13\" name=\"name13\" />" +
        "<Person ID=\"14\" name=\"name14\" />" +
        "</People>";

and I load as below:

 XDocument contentXML = XDocument.Parse(myContent);

then I iterate over all them:

 IEnumerable<XElement> people = contentXML.Elements();
 foreach (XElement person in people)
 {
     var idPerson = person.Element("Person").Attribute("ID").Value;
     var name = person.Element("Person").Attribute("name").Value
     // print the person ....
 }

The problem is that I only obtain the first person, not the rest. It says people has 1 element and it should have 14.

Any ideas?

Upvotes: 1

Views: 474

Answers (1)

Jeff Yates
Jeff Yates

Reputation: 62377

The problem is that you are asking for Elements() from the document root. There is only one element at this point, People.

What you actually want to do is something like:

var people = contentXML.Element("People").Elements()

Therefore, your loop would look something like:

IEnumerable<XElement> people = contentXML.Element("People").Elements();
foreach ( XElement person in people )
{
    var idPerson = person.Attribute( "ID" ).Value;
    var name = person.Attribute( "name" ).Value;
    // print the person ....
}

This will iterate over each of the Person elements as you intend.

Upvotes: 2

Related Questions