Read all descendants of a single element

I have a following XML file:

<data>
    <set1>
        <entry>Entry #1</entry>
        <entry>Entry #2</entry>
    </set1>
</data>

and I'm trying to read all the descendants of the SET element. Im not sure If I'm confusing terms like element and descendant, so Im just gonna stop using them for now :)

Here is the C# code that I use:

List<String> list = new List<String>();
XDocument xml = XDocument.Load("file.xml");

var desc = xml.Descendants("set1");
foreach (var entry in desc) {
    list.add(entry.Value);
    Console.Write("element: " + entry.Value);
}

But instead of two lines of console output "Entry #1" and "Entry #2" I only get one "Entry #1Entry #2". Thanks for your help!

Upvotes: 0

Views: 692

Answers (2)

ispiro
ispiro

Reputation: 27673

Change to

var desc = xml.Descendants("set1").Descendants();

And also

Console.WriteLine

I just tried it and it works.

The error is that Descendants("set1") does not give you the descendants of set1. It gives you the xml's root descendants that are called set1.

As for the Console.WriteLine - it adds a newline at the end of what it writes.

Upvotes: 1

Thirisangu Ramanathan
Thirisangu Ramanathan

Reputation: 614

Something Like :

 var desc = xd.Descendants("set1").Elements("entry");

Upvotes: 2

Related Questions