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