Thursday, May 1, 2008

XDocument - Selecting a single element value

XDocument is a new class that represents an XML document. It's a replacement to the XmlDocument and falls under the System.XML.LINQ namespace. When it comes time to selecting node values, you can say good-bye to XPath. Here is an example of selecting just one value from XML.
<Persons>
  <Person>
    <PersonId>1</PersonId>
    <PersonName>Mark</PersonName>
  </Person>
  <Person>
    <PersonId>2</PersonId>
    <PersonName>Matt</PersonName>
  </Person>
</Persons>
Say you want to select the first PersonName. You can write code like this:
XDocument ds = XDocument.Load("MyXml.xml");
string value = ds.Element("Persons").Element("Person").Element("PersonName").Value;
When you look for Element("Persons"), the XDocument is going to search for the FIRST match.

More Info: MSDN: XContainer.Element Method