Mikael Sauriol Saad
Mikael Sauriol Saad

Reputation: 122

C# reading xml inside certain node

I need help. I'm trying to figure out a way to read inside a bracket like this one:

<group id = "56"> 
<name>Counter</name> 
</group>

In the code, there are mulitiple places where the same pattern comes back, and I would like to get all the group id number's and their name.

This is my code:

        XDocument doc = XDocument.Parse(_XmlFile);
        var results = doc.Descendants("group").Select(x => new
        {
            id = (int)x.Attribute("id"),
            name = x.Attribute("name").Value,
        }).ToList();

        Console.WriteLine(results);

Thanks

Upvotes: 0

Views: 128

Answers (3)

derpirscher
derpirscher

Reputation: 17382

Your code looks quite OK, but name is an element and not an attribute, so it should be

XDocument doc = XDocument.Parse(_XmlFile);
var results = doc.Descendants("group").Select(x => new
{
    id = (int)x.Attribute("id"),
    name = (string)x.Element("name"),
}).ToList();

foreach (var x in results)
    Console.WriteLine("id: {0}   name: {1}", x.id, x.name);

Upvotes: 1

D&#225;vid Moln&#225;r
D&#225;vid Moln&#225;r

Reputation: 11573

"Name" is not an attribute, but a child node. The solution is something like this:

XDocument doc = XDocument.Parse(_XmlFile);
var results = doc.Descendants("group").Select(x => new
{
    id = int.Parse(x.Attribute("id").Value),
    name = x.Descendants("name").First().Value
}).ToList();

Upvotes: 0

Ivo Kazimirs
Ivo Kazimirs

Reputation: 31

Use GetElementsByTagName method.

Here is the microsoft article explaining it with examples. https://msdn.microsoft.com/en-us/library/dc0c9ekk(v=vs.110).aspx

Upvotes: 0

Related Questions