1

I have the following xml in a file:

<Person>
    <Name first="John" last="Doe" />
</Person>

I loaded the xml document with XDocument.Load, but I can't seem to get the values of the first and last attribute.

I tried:

var q = from n in rq.Element("Name")
        select n;  //but q is null after this.
1
  • Does it even compile? The Element Method returns an XElement, which is not enumerable (or queryable), so that LINQ expression should fail to compile. I guess you mean the Elements Method (plural). Commented May 12, 2011 at 23:11

1 Answer 1

4

Here's an example that should work with your XML file:

var doc = XDocument.Load(...);

var query = from node in doc.Root.Elements("Name")
            select new           //      ↑
            {
                First = (string)node.Attribute("first"),
                Last  = (string)node.Attribute("last")
            };

foreach (var item in query)
{
    Console.WriteLine("{1}, {0}", item.First, item.Last);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think it was compiling, but I was doing doc.Element instead of doc.Root.Elements.
How can I get the value for the first and last attributes from query? I tried query.Select(x=>x.first), but that doesn't work.

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.