Criv
Criv

Reputation: 11

parse XDocument for attributes

I have tried to parse an XML file like this:

<books>
   <book>
      <attr name="Moby Dick">Moby Dick is a classic</attr>
      <attr isbn="isbnNumber">123456789</attr>
   </book>
</books>

How can I get the value of "123456789"? I don't really need the first attribute.

I tried reading these in a foreach loop getting XElements but I keep getting a NULL object exception.

foreach(XElement xe in XDoc.Attribute("attr"))
{
   string str = xe.Attribute("isbnNumber").Value   // NULL EXCEPTION HERE
} 

Thanks in advance...

Upvotes: 1

Views: 1805

Answers (3)

Reddog
Reddog

Reputation: 15579

You could try using the XPathSelectElement() extension method [you'll need to use System.Xml.XPath to get them].

E.g.

var isbn = xDoc.XPathSelectElement("//book/attr[@isbn='isbnNumber']").Value

PS. A good XPath tester is at: http://www.yetanotherchris.me/home/2010/6/7/online-xpath-tester.html

Upvotes: 2

user544921
user544921

Reputation: 11

Well, I can't figure out how to respond to the individual answers..... but I implemented them both and they both work.

I am going with Reddog's answer as it is a little more straightforward and being new to LINQ it is the easiest as of now for readability.

Thanks for the responses!

Upvotes: 0

Josh
Josh

Reputation: 69272

123456789 is actually the value of an element, not an attribute. What you want can be done like so:

XElement attr = xDoc.Descendants("attr")
                    .FirstOrDefault( x=> 
                        (string)x.Attribute("isbn") == "isbnNumber"
                    );

string isbn = (string)attr;

You could even make it one line but this might be easier to read if you're new to LINQ to XML.

Upvotes: 1

Related Questions