Xaisoft
Xaisoft

Reputation: 46591

Querying xml returns null when using Linq to XML

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.

Upvotes: 1

Views: 1120

Answers (1)

dtb
dtb

Reputation: 217263

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);
}

Upvotes: 4

Related Questions