kyle_13
kyle_13

Reputation: 1233

Parsing XML with a Namespace in the root element in C#

I am having trouble parsing the following XML in C#, because of the "xmlns" attribute in the root.

<CaptureResponse xmlns="http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01">
    <CaptureResult>
        <State>Open</State>
    </CaptureResult>
</CaptureResponse>

How would I, for example, check for the existence of the element in C# with the above xml? The below does not work.

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(response);
        if (doc.SelectSingleNode("CaptureResponse") != null) 
        {}

Upvotes: 0

Views: 310

Answers (2)

Bensonius
Bensonius

Reputation: 1541

An XmlNamespaceManager is needed. You create one and add a reference to the namespace in your XML document.

The "s" in the AddNamespace() is an example of a Namespace prefix that can be used in your selection queries instead of having to prefix every node with the full Namespace. S can be replaced with whatever prefix you wish to use.

XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("s", "http://mws.amazonservices.com/schema/OffAmazonPayments/2013-01-01");
XmlNode myNode = doc.SelectSingleNode("s:CaptureResponse", nsMgr);

Upvotes: 1

Steve Wellens
Steve Wellens

Reputation: 20638

Your XPath is ambiguous. Try this:

XmlNode Root = doc.SelectSingleNode("/CaptureResponse");

Upvotes: 0

Related Questions