xml XPath 中的元素计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7393541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
count of element in XPath
提问by hudi
...
<element>
<e:Element1 xmlns:e="mynamespace" > ... </.. >
<e:Element1 xmlns:e="mynamespace" > ... </.. >
<e:Element1 xmlns:e="mynamespace" > ... </.. >
<a/>
</element>
...
and this XPath:
和这个 XPath:
//*[local-name()='element']/count(*)return 4 what is OK.
but now I wanna know count of element1 what is 3. I try a lot of possibilities but with no succes. I have to use local-name and namespace-uri()
//*[local-name()='element']/count(*)返回 4 什么都行。但现在我想知道 element1 的计数是 3。我尝试了很多可能性,但没有成功。我必须使用本地名称和namespace-uri()
回答by Anton Vidishchev
You can try the following:
您可以尝试以下操作:
count(//element/Element1[namespace-uri()='mynamespace'])
回答by Michael Kay
If you are using XPath from an environment such as Java or C#, you should first bind a prefix to the namespace, which depends on the API you are using, but will be something like
如果您在 Java 或 C# 等环境中使用 XPath,则应首先将前缀绑定到命名空间,这取决于您使用的 API,但类似于
xpath.declareNamespace("f", "mynamespace")
and then evaluate the XPath expression
然后计算 XPath 表达式
count(element/f:Element1)
I deliberately chose a different prefix from the one in your source document just to show that you can use any prefix you like, but of course your code is more readable if you are consistent in your choice of prefixes.
我特意选择了与源文档中的前缀不同的前缀,只是为了表明您可以使用任何喜欢的前缀,但当然,如果您选择的前缀一致,则您的代码更具可读性。
回答by andyb
For the following valid XML
对于以下有效的 XML
<element>
<e:Element1 xmlns:e="mynamespace"></e:Element1>
<e:Element1 xmlns:e="mynamespace"></e:Element1>
<e:Element1 xmlns:e="mynamespace"></e:Element1>
<a/>
</element>
this XSL
这个 XSL
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:e="mynamespace">
<xsl:template match="/">
<xsl:value-of select="count(element/e:Element1)"/>
</xsl:template>
</xsl:stylesheet>
gives the desired output of 3.
给出所需的输出3。
The selector is qualified with the correct namespace.
选择器使用正确的命名空间进行限定。
You were close in your question and you could drop the namespace and use the following XSL instead:
您的问题很接近,您可以删除命名空间并改用以下 XSL:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:value-of select="count(element/*[local-name()='Element1'])"/>
</xsl:template>
</xsl:stylesheet>

