如何使用 XPATH 从 XML 文档中选择不同的值? [英] How to select distinct values from XML document using XPATH?

查看:24
本文介绍了如何使用 XPATH 从 XML 文档中选择不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 XPATH 只为 XML 文档选择不同的元素?我曾尝试使用distinct-values"函数,但由于某种原因它不起作用..

How can I select only distinct elements for the XML document using XPATH?I've tried to use the 'distinct-values' function but it didn't work for some reason..

XML 类似于以下内容:

The XML is similar to the following:

<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/*)

So what I want to get is the list of distinct children of all the product elements.In the given example it would be - size,price,rating,year My xpath was something like : 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>

这篇关于如何使用 XPATH 从 XML 文档中选择不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆