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

后端 未结 2 1254
南旧
南旧 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:

    
       
          
             
          
       
    
    

    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.

提交回复
热议问题