0

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

5
  • Name isn't an attribute but a child node Commented May 3, 2017 at 17:42
  • 1. You cant cast XElement to int. You need to parse the Value which is a string. 2. name is not an attribute but a child element to group. Commented May 3, 2017 at 17:42
  • Can someone help me correct this? Commented May 3, 2017 at 17:44
  • @SaniSinghHuttunen: Actually, XNode has cast operators. Commented May 3, 2017 at 17:47
  • @SLaks: Indeed it does. My Bad... :) Well... It's actually XAttribute in this case... Which does not inherit from XNode... But XAttribute has the same cast operators as well... Commented May 3, 2017 at 17:53

3 Answers 3

1

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

Comments

0

Use GetElementsByTagName method.

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

1 Comment

If i use that, once I put group in the doc.GetElementsByTagName("group"), It returns all the rest of the xml.
0

"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();

2 Comments

You don't need the int.Parse part, but you can cast the XAttribute to int and x.Element("name") is the more accurate way to for getting the first child element of an XElement. Furthermore x.Descendants gets the children in all descendent levels. Maybe this is not desired. And if there is no descendant name your code will throw an exception
Thanks, you'r right. I did no see your answer before posting... :)

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.