Quick Tip: Using XPath to find nodes by attribute value

There are some things that I can just remember: phone numbers, locker combinations, and the like.  There are others that I have to lookup again and again and again.  XPath query syntax is one of the latter items.  Today, I'd like to talk a little about XPath queries.

The following XML contains a collection of "Friend" nodes.  Each node has attributes for name and birth date.  To keep this post to a reasonable length, I am going to limit the XML to 5 nodes.

<MyFriends>  <Friend name="Sam" birthMonth="July" birthDay="16" birthYear="1974" />  <Friend name="Pam" birthMonth="April" birthDay="7" birthYear="1967" />  <Friend name="George" birthMonth="February" birthDay="2" birthYear="1981" />  <Friend name="John" birthMonth="April" birthDay="11" birthYear="1972" />  <Friend name="Martha" birthMonth="August" birthDay="3" birthYear="1974" /></MyFriends>

After loading this XML into an XmlDocument, I can use XPath to query for the nodes of interest.

Since April is coming soon, I would like to get a list of my friends who has a birthday that month.  To do so, I query for Friend nodes where the value of the birthMonth attribute is "April".

// load the xml file into an XmlDocumentXmlDocument doc = new XmlDocument();doc.Load("myfriends.xml");XmlElement rootNode = doc.DocumentElement;// select the friends who have a birthday in AprilString query = "Friend[@birthMonth='April']";XmlNodeList friends = rootNode.SelectNodes(query);foreach(XmlElement friend in friends){    // TODO: display a reminder to buy a birthday card}

When the above snippet is run, two friends are returned: Pam and John.  The application can retrieve the desired information from the node and display an appropriate reminder.

Enjoy!
-- DK

Edit: Fix grammar

Disclaimer(s):
This posting is provided "AS IS" with no warranties, and confers no rights.