Wednesday, February 23, 2011

HOWTO: find descendant XElement in XDocument by its name recursively using LINQ with namespaces

If you want to use LINQ to locate XML nodes by their names and your XML contains namespace notations, be aware to specify namespaces looking for descendants.

XML Example:

<?xml version="1.0" encoding="utf-8"?>
<
MyDataStruct xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <
DataRoot xmlns="http://mydata.org/2011/1">
    <
Dispatch xmlns="http://mydata.org/2011/1">
      <
Target>
        <
Organisation>
          <
Comment></Comment>
          <
ID></ID>
        </
Organisation>
        <
System>
          <
ID>100</ID>
          <
Comment></Comment>
        </
System>
      </
Target>
      <
Source>
        <
Organisation>
          <
Comment></Comment>
          <
ID></ID>
        </
Organisation>
        <
System>
          <
ID>101</ID>
          <
Comment></Comment>
        </
System>
      </
Source>
    </
Dispatch>
  </
DataRoot>
</
MyDataStruct>

LINQ based recursive search operations:

XDocument xDoc = XDocument.Load(xmlFileName);

XElement xe1 = xDoc.Descendants("{http://mydata.org/2011/1}Target").First(); // locate first “Target” node
   XElement xe1 = xDoc.Descendants("{http://mydata.org/2011/1}Source").First()
                                  .Descendants("{http://mydata.org/2011/1}ID").First(); // locate “ID” subnode of“Source” node

UPDATE: seen also here -

http://stackoverflow.com/questions/566167/query-an-xdocument-for-elements-by-name-at-any-depth

Enjoy!

No comments: