XML: A namespace prefix is claimed to be not declared when it fact it is

后端 未结 2 1225
南旧
南旧 2021-01-21 04:30

We\'ve got a web service that returns a very simple XML.




        
相关标签:
2条回答
  • 2021-01-21 05:02

    You've already answered the question, but it's worth understanding why this is.

    The namespace that an element is in cannot be determined solely by the namespace prefix. To find what namespace an element named t:foo is in, you have to search up the ancestor-or-self axis until you find the nearest node that defines the namespace for t:. For instance:

    <t:one xmlns:t="ns-one">
       <t:one>
          <t:two xmlns:t="ns-two">
             <t:two/>
          </t:two>
       </t:one>
    </t:one>
    

    In that document, every element whose name is one is in the ns-one namespace, and every element whose name is two is in the ns-two namespace. You can tell that the deepest element in that document is in ns-two not because t: intrinsically means ns-two, but because if you search up the ancestor-or-self axis, the first element that you hit with an xmlns:t attribute on it - its parent - tells you the namespace.

    Given that, which nodes should the XPath expression //t:* match? It's impossible to say, because what namespace t: is mapped to changes throughout the document.

    Also, namespace prefixes are temporary, but namespaces are permanent. If you know that one is in ns-one, you really, truly don't care whether its prefix is t: or x: or if it has no prefix at all and just an xmlns attribute.

    When you're querying an XML document with XPath, you need a way of specifying what namespace a given element is in. And that's what SelectionNamespaces in a DOMDocument, or a namespace manager in C#, or whatever are for: they tell you what namespaces the prefixes in your XPath queries represent. So if I've set the prefix a: to ns-one, the XPath //a:one will find me all of the elements named one in the ns-one namespace, irrespective of what the actual prefix they're using in the document I'm searching is.

    This is a little counterintuitive when you're first learning it, but really, it's the only way that makes any sense at all.

    0 讨论(0)
  • 2021-01-21 05:05

    Surprisingly enough (for me), this is the default behaviour for XPath. By default, namespace prefixes are not allowed in an XPath query.

    To resolve this, one must register desired prefixes with SelectionNamespaces property of the DOMObject.

    objXML.setProperty("SelectionNamespaces", "xmlns:t='http://our.website.com/ns/'")
    

    After that one can use expressions qualified with t: in XPath queries. This also resolvers the original problem that forced us to use XmlNamespaceDeclarations in the first place.

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