Querying XML Attributes

I’ve been taking XML drills through Inner Working’s online certification. New ways of handling XML data have made it easier than ever. However, there are some pitfalls when querying XML. Below is an example. If you want to get and “ID” attribute from a document element, here is what you might do:

string documentID;
//Correct: Referencing the "Document Element" variable
documentID = xmldoc.DocumentElement.Attributes["id"].InnerXml;
//Correct: Selecting the "Document" node"
documentID = xmldoc.SelectSingleNode("document").Attributes["id"].InnerXml;
//Wrong: Selecting the "Document" node"
documentID = xmldoc.DocumentElement.SelectSingleNode("document").Attributes["id"].InnerXml;
Advertisements