Wednesday, April 30, 2008

LINQ to XML - Namespaces

Adding on to yesterday's post, you might come across xml that has a namespace defined. You'll have to handle this with the XNamespace object.
XML with namespace:
<?xml version="1.0" standalone="yes"?>
<MyDataSet xmlns="http://tempuri.org/MyDataSet.xsd">
  <Person>
    <PersonId>1</PersonId>
    <PersonName>Mark</PersonName>
  </Person>
  <Person>
    <PersonId>2</PersonId>
    <PersonName>Matt</PersonName>
  </Person>
</MyDataSet>
Querying the XML:
XDocument ds = XDocument.Load(Resources.SimpleXmlFileWithNamespacePath);
XNamespace ns = "http://tempuri.org/MyDataSet.xsd";
XName xNamePerson = ns + "Person";
XName xNamePersonName = ns + "PersonName";

var personNames = from person in ds.Descendants(xNamePerson)
              select new
              {
                  PersonName = person.Element(xNamePersonName).Value
              };
The XName class provides a way to combine a namespace and an element name.

More Info: MSDN: XNamespace Class
MSDN: XName Class