Showing posts with label XDocument. Show all posts
Showing posts with label XDocument. Show all posts

Monday, May 5, 2008

XDocument - Selecting a multiple elements

Say we want to select all Person elements in this XML:
<Persons>
  <Person>
    <PersonId>1</PersonId>
    <PersonName>Mark</PersonName>
  </Person>
  <Person>
    <PersonId>2</PersonId>
    <PersonName>Matt</PersonName>
  </Person>
</Persons>
You can use the following code:
string returnValue = string.Empty;
XDocument ds = XDocument.Load("MyXml.xml");
var people = ds.Element("Persons").Elements("Person");

foreach (var singlePerson in people)
{
    returnValue += singlePerson.Element("PersonName").Value + "\r\n";
}

Console.WriteLine(returnValue);
The result will be:
Mark
Matt


More Info: MSDN: XContainer.Elements Method

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