colobusgem
colobusgem

Reputation: 473

c# XmlDocument SelectNodes isn't returning nodes

I am trying to make a generic XmlParsing method. Take the Xml as such:

<body>
<section>
    <subsection1>
        ...
    </subsection1>
    <subsection2>
        ...
    </subsection2>
</section>
<section>
    <subsection1>
        ...
    </subsection1>
    <subsection2>
        ...
    </subsection2>
</section>
</body>

I am trying to grab all "section" nodes without knowing how deep they are or their parent nodes names.

So far I have (my XML is in string format)

        XmlDocument xml = new XmlDocument();
        xml.LoadXml(XMLtoRead);

        XmlNodeList nodes = xml.DocumentElement.SelectNodes("//section");

However the node count is always 0. I was under the impression the "//" prefix recursivly searches through the document for the nodes named.

My real XML is a SOAP reply:

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">


<soap:Body>
    <Response xmlns="http://tempuri.org/">

Upvotes: 2

Views: 2212

Answers (1)

LocEngineer
LocEngineer

Reputation: 2917

In that case it is not generic but specific to your kind of SOAP replies. ;-) Try this:

var ns = new XmlNamespaceManager(xml.NameTable);
ns.AddNamespace("ns", "http://tempuri.org/");
XmlNodeList nodes = xml.DocumentElement.SelectNodes("//ns:section", ns);

Upvotes: 5

Related Questions