简体   繁体   中英

Namespace of specific XML Node in c#

I have the following XML structure:

<?xml version="1.0" encoding="utf-16"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <StoreResponse xmlns="http://www.some-site.com">
      <StoreResult>
        <Message />
        <Code>OK</Code>
      </StoreResult>
    </StoreResponse>
  </soap:Body>
</soap:Envelope>

I need to get the InnerText from Code out of this document and I need help with the appropriate XPATH statement.

I'm really confused by XML namespaces. While working on a previous namespace problem in another XML document, I learned, that even if there's nothing in front of Code (eg ns:Code ), it is still part of a namespace defined by the xmlns attribute in its parent node. Now, there are multiple xmlns nodes defined in parents of Code . What is the namespace that I need to specify in an XPATH statement? Is there such a thing as a "primary namespace"? Do childnodes inherit the (primary) namespace of it's parents?

The namespace of the <Code> element is http://www.some-site.com . xmlsn:xxx means that names prefixed by xxx: (like soap:Body) have that namespace. xmlns by itself means that this is the default namespace for names without any prefix.

An example of using an XDocument (Linq) approach:

XNamespace ns = "http://www.some-site.com";

var document = XDocument.Parse("your-xml-string");
var elements = document.Descendants( ns + "StoreResult" )

Descendant elements will inherit the last immediate namespace. In your example you will need to create two namespaces one for the soap envelope and a second for "some-site".

Here's an option I found in this question: Weirdness with XDocument, XPath and namespaces

var xml = "<your xml>";
var doc = XDocument.Parse(xml); // Could use .Load() here too
var code = doc.XPathSelectElement("//*[local-name()='Code']");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM