【发布时间】:2012-03-01 13:24:06
【问题描述】:
我有一个 xml 文件和相应的 xsl 文件。我有以下代码行,它在代码中重复了很多次。我需要找出 status 的值是 0 的多少倍?我该怎么做?
提前致谢
【问题讨论】:
-
你可能想检查这个线程 - 看起来非常相似stackoverflow.com/questions/721963/…
我有一个 xml 文件和相应的 xsl 文件。我有以下代码行,它在代码中重复了很多次。我需要找出 status 的值是 0 的多少倍?我该怎么做?
提前致谢
【问题讨论】:
使用 xpath count(//UserValue[@title = 'status' and @value = 0])。
【讨论】:
输入 XML:
<?xml version="1.0" encoding="utf-8"?>
<root>
<child1>
<UserValue type="int" value="0" title="status"></UserValue>
<UserValue type="int" value="0" title="status"></UserValue>
<UserValue type="int" value="0" title="status"></UserValue>
<UserValue type="int" value="0" title="status"></UserValue>
<UserValue type="int" value="0" title="status"></UserValue>
<UserValue type="int" value="0" title="status"></UserValue>
<UserValue type="int" value="0" title="statusss"></UserValue>
</child1>
<child2>
<UserValue type="int" value="0" title="status"></UserValue>
<UserValue type="int" value="0" title="status"></UserValue>
<UserValue type="int" value="0" title="status"></UserValue>
<UserValue type="int" value="0" title="status"></UserValue>
<UserValue type="int" value="0" title="status"></UserValue>
<UserValue type="int" value="0" title="status"></UserValue>
<UserValue type="int" value="0" title="status"></UserValue>
</child2>
</root>
这将计算整个文件中具有Value='0' 属性和title='status' 属性的UserValue 节点的数量
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns="http://www.plmxml.org/Schemas/PLMXMLSchema">
<xsl:output method="xml" indent="yes"/>
<xsl:variable name="count_nodes" select="count(//ns:UserValue[@value='0' and @title='status'])"/>
<xsl:template match="/">
<xsl:element name="count">
<xsl:value-of select="$count_nodes"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
输出:
<?xml version="1.0" encoding="utf-8"?>
<Count>2</Count>
根据 Dimitre 对性能差异的评论进行编辑:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns="http://www.plmxml.org/Schemas/PLMXMLSchema">
<xsl:output method="xml" indent="yes"/>
<xsl:variable name="count_nodes" select="count(/*/*/ns:UserData/ns:UserValue[@title = 'status' and @value= '0'])"/>
<xsl:template match="/">
<xsl:element name="count">
<xsl:value-of select="$count_nodes"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
【讨论】:
XML 文档位于默认命名空间中。
因此,解决方案必须考虑到这一点:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:x="http://www.plmxml.org/Schemas/PLMXMLSchema">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:value-of select="count(//x:UserValue[@title = 'status' and @value= '0'])"/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于提供的 XML 文档时:
计算返回指定节点计数的 XPath 表达式并输出该计数:
2
请注意:使用 // 伪运算符的 XPath 表达式可能非常慢,因此如果 XML 文档的结构是众所周知的,则应使用等效的 XPath 表达式, '不包含//。
例如,如果我正确理解了提供的文档的结构,这是一个更好的XPath表达式:
count(/*/*/x:UserData/x:UserValue[@title = 'status' and @value= '0'])
【讨论】: