第一个问题:有什么方法可以获取节点属性的名称?
<node attribute1="value1" attribute2="value2" />
第二个问题:有没有一种方法可以将属性和值作为值对获得?情况如下:
<node attribute1="10" attribute2="0" />
我想以value> 0的这种方式获取所有属性:“attribute1 = 10”。
最佳答案
First question: is there any way to get the name of a node's attributes?
<node attribute1="value1" attribute2="value2" />
是:
此XPath表达式(当
node
是上下文(当前)节点时):name(@*[1])
产生第一个属性的名称(顺序可能取决于实现-取决于实现)
和此XPath表达式(当
node
是上下文(当前)节点时):name(@*[2])
产生第二个属性的名称(顺序可能取决于实现方式)。
Second question: is there a way to get attributes and values as value pairs? The situation is the following:
<node attribute1="10" attribute2="0" />
I want to get all attributes where value>0 and this way: "attribute1=10".
此XPath表达式(当名为“
attribute1
”的属性是上下文(当前)节点时):concat(name(), '=', .)
产生字符串:
attribute1=value1
和此XPath表达式(当节点
node
是上下文(当前)节点时):@*[. > 0]
选择上下文节点的所有属性,这些属性的值是一个大于0的数字。
在XPath 2.0中,可以将它们组合在一个XPath表达式中:
@*[number(.) > 0]/concat(name(.),'=',.)
得到(在这种情况下)这个结果:
attribute1=10
如果您使用功能不那么强大的XPath 1.0 ,则需要将XPath表达式嵌入宿主语言中,例如XSLT 。以下XSLT 1.0转换:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/*">
<xsl:for-each select="@*[number(.) > 0]">
<xsl:value-of select="concat(name(.),'=',.)"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
应用于此XML文档时的:
<node attribute1="10" attribute2="0" />
产生完全相同的结果:
attribute1=10
关于XPath 1查询和属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/694298/