Extract XML element from XmlDocument

2.1k Views Asked by At

I'm still new on XML and am having trouble on this project I'm working on. I need to extract a specific xml element from a C# XmlDocument. In the below example, I want to pull out the ns:AMOUNT element from the RATING tag (193.13 should be the result). How would you correctly do this? Thanks so much!

<?xml version="1.0" encoding="UTF-8" ?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <ns:getResp xmlns:ns="http://example">
            <ns:jobReturn>
                <ns:ITEM>
                    <ns:AMOUNT>24.7</ns:AMOUNT>
                </ns:ITEM>
                <ns:RATING>
                    <ns:RefNum>1234567890</ns:RefNum>
                    <ns:AMOUNT>193.13</ns:AMOUNT>
                </ns:RATING>
            </ns:jobReturn>
        </ns:getResp>
    </soapenv:Body>
</soapenv:Envelope>
1

There are 1 best solutions below

0
On BEST ANSWER

I think your problem happens that you need XmlNamespaceManager to deal with ns part. so

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"your.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("ns", "http://example");
XmlNode node = xmlDoc.SelectSingleNode("//ns:RATING/ns:AMOUNT", ns);
var result = node.InnerText;