Weirdness with XDocument, XPath and namespaces

后端 未结 2 1740
灰色年华
灰色年华 2020-12-09 10:44

I have an XML document that looks like this:



        
相关标签:
2条回答
  • In addition to the correct remark by @Mads-Hansen, you have the typical problem of not defining a (nonempty) prefix for one of the namespaces.

    Remember: XPath considers any unprefixed name to be in "no namespace".

    Therefore this is wrong:

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

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

    To do it correctly:

    oManager.AddNamespace("xxx", "http://url1");      
    Source.XPathSelectElement("//xxx:kmsg", oManager)
    
    0 讨论(0)
  • 2020-12-09 11:24

    The namespace-URI's declared in your source XML do not match the namespace-URI's that you are registering with your XmlNamespaceManager.

    In your source XML:

    1. The anonymous namespace (no prefix) has the namespace-uri: http://url1
    2. The env namespace prefix has the namespace-uri: url1

    In your XmlNamespaceManager you declared:

    1. The anonymous namespace (no prefix) has the namespace-uri: http://xml.kerridge.net/k8msg
    2. The env namespace prefix has the namespace-uri: http://xml.kerridge.net/k8msgEnvelope

    The namespace-uri values have to match, otherwise you are selecting different element names and will never get a match.

    0 讨论(0)
提交回复
热议问题