更新时间:2023-11-24 17:01:04
这是 XPath/XSLT 中最常见的常见问题之一:
XPath 将无前缀的元素名称解释为属于无命名空间",这就是当仅将其无前缀名称指定为节点测试时,不选择具有属于默认(非空)命名空间的无前缀名称的元素的原因一个 XPath 表达式.
XPath interprets an unprefixed element name as belonging to "no namespace" and this is the reason elements with unprefixed names belonging to a default (nonempty) namespace aren't selected when only their unprefixed name is specified as a node-test in an XPath expression.
解决方案是:
创建一个命名空间绑定,其中前缀(比如 "x"
)与默认命名空间相关联,然后指定 x:elementName
而不是 元素名称
.
Create a namespace binding where a prefix (say "x"
) is associated with the default namespace, then specify x:elementName
instead of elementName
.
使用冗长、丑陋和不可靠的表达式,例如:*[name() = 'elementName']
Use long, ugly and unreliable expressions like: *[name() = 'elementName']
这是使用上述方法的 XSLT 转换1.:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:a="http://some_url">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:value-of select=
"/root/items/item/details/a:data/a:weight"/>
</xsl:template>
</xsl:stylesheet>
在提供的 XML 文档上应用此转换时(使用 Saxon 6.5.4 或任何其他兼容的 XSLT 1.0 处理器):
<root>
<items>
<item>
<title>Item</title>
<details>
<data xmlns="http://some_url">
<length>10</length>
<weight>1.2</weight>
</data>
</details>
</item>
</items>
</root>
选择正确/想要的节点并将其字符串值复制到输出:
1.2