gpt4 book ai didi

xml - 如何使用 XPATH 从 XML 文档中选择不同的值?

转载 作者:数据小太阳 更新时间:2023-10-29 01:40:30 28 4
gpt4 key购买 nike

我如何才能使用 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>

所以我想得到的是所有产品元素的不同子项的列表。在给定的示例中,它将是 - 尺寸、价格、等级、年份我的 xpath 类似于:distinct-values(catalog/product/*)

最佳答案

在 XPath 2.0 中:

distinct-values(/*/*/*/name(.))

在 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>

当此转换应用于提供的 XML 文档时,会产生所需的结果:

size price rating year

更高效的 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>

关于xml - 如何使用 XPATH 从 XML 文档中选择不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2871707/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com