XPath名称空间通配符最佳实践

Chi*_*pal 1 xml xpath

在我们的例子中,我们有这样的动态XML标记

<ab:SomeProcessResponse xmlns:ab="http://something.com/xyz"
                        xmlns:cd="http://something.com/lmno">
Run Code Online (Sandbox Code Playgroud)

有时我可能会得到回应

<def:SomeProcessResponse xmlns:def="http://something.com/xyz"
                         xmlns:cd="http://something.com/lmno">
Run Code Online (Sandbox Code Playgroud)

SomeProcessResponse在这种情况下选择节点时应遵循的最佳实践是什么?

kjh*_*hes 5

选择命名空间XML元素的最佳实践是指定命名空间,而不是通过任何类型的“通配符”机制忽略它。

For compliant XPath processors, there is always a mechanism to allow the binding of a namespace prefix (eg: ab) to a namespace URI (eg: http://something.com/xyz). It is not even necessary to use the same namespace prefix (ab) as is being used in the source XML; only the namespace URI (http://something.com/xyz) must match. The only challenge, however, is that XPath itself does not have a mechanism for binding namespace prefixes to namespace URIs. How to do so is dependent upon the facilities offered by the library (eg: libxml2, javax.xml.xpath, etc) or hosting language (eg: XSLT).

In order to provide a pure XPath answer, or sometimes because of (commonly irrational) aversion to namespaces, you'll sometimes see a wildcard mechanism used. A common wildcard mechanism is to use local-name() to only reference the local name (eg: SomeProcessResponse) independent of the namespace. The problem with this is that not only does it bypass the namespace prefix (eg: ab), it also bypasses the namespace URI (http://something.com/xyz), and the namespace URI is integral to the name and an important part of associating other facilities with the element. Such other facilities include validation and OO class mappings, for example.

因此,是的,存在用于避开名称空间的通配符机制,但是最佳实践是使用托管语言/库的功能将名称空间前缀与名称空间URI相关联,而不是通过通配符避免名称空间