Does this need to be an XPath expression or can you use Linq with the XDocument system.
For example.
var xDocument = XDocument.Parse(@"<bookstore>
<book>
<bookID>100</bookID>
<name> The cat in the hat </name>
</book>
<book bookID=""90"">
<name> another book </name>
</book>
<book>
<bookID>103</bookID>
<name> a new book </name>
</book>
</bookstore>");
foreach (var xBook in xDocument.Descendants("book"))
{
var bookIdNode = xBook.Elements("bookID").FirstOrDefault();
int bookId = 0;
///there is a book id as an element
if (bookIdNode != null)
{
//invalid book id.. should be an int
if (!int.TryParse(bookIdNode.Value, out bookId))
continue;
}
else
{
var bookIdAttr = xBook.Attributes("bookID").FirstOrDefault();
if (bookIdAttr == null || !int.TryParse(bookIdAttr.Value, out bookId))
continue;
}
if (bookId == 0)
continue;
//else we got our book id
}
This code is quite simple, just enumerates over the descendants with the element name book. It first checks if there is an element named bookID (case sensitive). If there is it attempts to parse the book id out as an int using the method int.TryParse().
If there are no bookID elements it next checks if there are any attributes with the name bookID and grabs the first instance (or null) using FirstOrDefault() extension method. If there is an instance of the bookID attribute it also try to parse the int using the int.TryParse() method.
By the end of the small snippet we have then check if the bookId is 0 if it is zero we can assume something went wrong. However this shouldnt happen as the logic should keep enumerating and forget about Elements without a bookID element or bookID attribute.