如何使用XPATH仅为XML文档选择不同的元素?我尝试使用'distinct-values'函数但由于某些原因它不起作用..
XML类似于以下内容:
<catalog>
<product>
<size>12</size>
<price>1000</price>
<rating>1</rating>
</product>
<product>
<size>10</size>
<price>1000</price>
<rating>1</rating>
<year>2010</year>
</product>
</catalog>
Run Code Online (Sandbox Code Playgroud)
所以我想得到的是所有产品元素的不同子元素列表.在给定的例子中,它将是 - 大小,价格,评级,年份我的xpath类似于:distinct-values(catalog/product/*)
Dim*_*hev 18
在XPath 2.0中:
distinct-values(/*/*/*/name(.))
Run Code Online (Sandbox Code Playgroud)
在XPath 1.0中,无法使用单个XPath表达式生成此内容.
使用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=
"/*/*/*[not(../following::*/*
[not(name() = name(current()))]
)
]">
<xsl:value-of select="concat(name(), ' ')"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
在提供的XML文档上应用此转换时,将生成所需的结果:
size price rating year
Run Code Online (Sandbox Code Playgroud)
使用密钥更高效的XSLT 1.0转换:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:key name="kpchildByName"
match="product/*" use="name()"/>
<xsl:template match="/">
<xsl:for-each select=
"/*/*/*
[generate-id()
=
generate-id(key('kpchildByName', name())[1])
]">
<xsl:value-of select="concat(name(), ' ')"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
您需要元素名称的不同值 - 例如:
distinct-values($catalog/product/*/name(.))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58757 次 |
| 最近记录: |