Searching in XML with XPath

In its simplest form, XPath may look similar to directory file paths. Here's an example using the XML document containing a customer list. This document is shown in Example 14-2 and is reproduced here for convenience:

<Customers>
  <Customer FirstName="Orlando" LastName="Gee">
    <EmailAddress>orlando0@hotmail.com</EmailAddress>
  </Customer>
  <Customer FirstName="Keith" LastName="Harris">
    <EmailAddress>keith0@hotmail.com</EmailAddress>
  </Customer>
  <Customer FirstName="Donna" LastName="Carreras">
    <EmailAddress>donna0@hotmail.com</EmailAddress>
  </Customer>
  <Customer FirstName="Janet" LastName="Gates">
    <EmailAddress>janet1@hotmail.com</EmailAddress>
  </Customer>
  <Customer FirstName="Lucy" LastName="Harrington">
    <EmailAddress>lucy0@hotmail.com</EmailAddress>
  </Customer>
</Customers>

Example 14-3 lists the code for the example.

Example 14-3. Searching an XML document using XPath

using System; using System.Collections.Generic; using System.Xml; namespace Programming_CSharp { public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } // Overrides the Object.ToString( ) to provide a // string representation of the object properties. public override string ToString( ) { return string.Format("{0} {1}\nEmail: {2}", FirstName, LastName, EmailAddress); } } public class Tester { private static XmlDocument CreateCustomerListXml( ) { List<Customer> customers = CreateCustomerList( ); XmlDocument customerXml ...

Get Programming C# 3.0, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.