Weirdness with XDocument, XPath, and Namespaces

I have an XML document that looks like this:

<kmsg xmlns="http://url1" xmlns:env="url1" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://location that does not exist.xsd"> <header> <env:envelope> <env:source branch="907" machine="0" password="J123"/> </env:envelope> </header> <body> <OrderResponse xmlns="urn:schemasbasdaorg:2000:orderResponse:xdr:3.01"> <SomeMoreNodes/> </OrderResponse> </body> 

It has no schemas available, despite the fact that namespaces are specified (I get this from an external source, so I have no control). I parse it with XDocument, but keep getting null values ​​for elements outside the env namespace. I create an XDocument as follows:

 XDocument Source = XDocument.Load("Testfile.xml"); XmlNamespaceManager oManager = new XmlNamespaceManager(new NameTable()); oManager.AddNamespace(String.Empty, "http://xml.kerridge.net/k8msg"); oManager.AddNamespace("env", "http://xml.kerridge.net/k8msgEnvelope"); 

Then I try to get the values:

? Source.XPathSelectElement ("// kmsg", oManager)

zero

? Source.XPathSelectElement ("// header", oManager)

zero

? Source.XPathSelectElement ("// env: source", oManager)

Chooses the correct node

I assume this is because I did not configure the namespace manager correctly, but I cannot figure out how to fix it. Any help would be great.

thank

+12
c # xpath linq-to-xml xml-namespaces
Sep 15 2018-10-10T00:
source share
2 answers

In addition to the correct @ Mads-Hansen remark, you have a typical problem of not defining a (non-empty) prefix for one of the namespaces.

Remember . XPath believes that any unsigned name is in "no namespace."

Therefore this is not true :

 Source.XPathSelectElement("//kmsg", oManager) 

This XPath expression wants to select all kmsg elements that are in the "without namespace" and does not select anything correctly, because any kmsg elements in the provided XML document are in the namespace "http://url1" and not in "no namespaces. "

To do it right :

 oManager.AddNamespace("xxx", "http://url1"); Source.XPathSelectElement("//xxx:kmsg", oManager) 
+22
Sep 15 '10 at 13:17
source share

The URI namespace declared in the source XML file does not match the identifier of the URI namespace that you register with the XmlNamespaceManager .

In your original XML:

  • In the anonymous namespace (without a prefix) there is a namespace-uri: http://url1
  • The env space prefix has a uri namespace: url1

In XmlNamespaceManager you declared:

  • In the anonymous namespace (without a prefix) there is a uri namespace: http://xml.kerridge.net/k8msg
  • The env space prefix has a uri namespace: http://xml.kerridge.net/k8msgEnvelope

The namespace-uri values ​​must match, otherwise you select different element names and you will never get a match.

+1
Sep 15 '10 at 11:24
source share



All Articles