XPath 获取唯一元素名称 [英] XPath to get Unique Element Names

查看:43
本文介绍了XPath 获取唯一元素名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 XPath 获取出现在 XML 文件中的所有元素的名称列表.但是,我不希望任何名称重复,因此不应匹配与前一个元素同名的元素.到目前为止,我有:

I want to use XPath to get a list of the names of all the elements that appear in an XML file. However, I don't want any names repeated, so an element with the same name as a preceding element should not be matched. So far, I've got:

*[not(local-name() = local-name(preceding::*))]

这可以正常执行,但会吐出重复项.为什么它会吐出重复项,我该如何消除它们?(我使用的是 Firefox 的 XPath 引擎.)

This executes alright but it spits out duplicates. Why does it spit out the duplicates and how can I eliminate them? (I'm using Firefox's XPath engine.)

推荐答案

您收到重复项,因为您的过滤器没有按照您认为的方式进行评估.

You are getting duplicates because your filter is not evaluating the way you think it is.

local-name() 函数返回节点集中第一个节点 的本地名称.

The local-name() function returns the local name of the first node in the nodeset.

谓词过滤器唯一起作用的情况是该元素碰巧与第一个前面的元素同名.

The only time your predicate filter would work is if the element happened to have the same name as the first preceding element.

我认为您无法使用纯粹的 XPATH 1.0 解决方案来完成您想要的工作.您可以在 XPATH 2.0 中执行此操作,但无法在 Firefox 中使用.

I don't think you will be able to accomplish what you want with a pure XPATH 1.0 soultion. You could do it in XPATH 2.0, but that would not work with Firefox.

XSLT 中,您可以使用 meunchien 方法 来完成你想要的.

In XSLT you can use the meunchien method to accomplish what you want.

下面是一个例子.您没有提供任何示例 XML,因此我将其保留为非常通用的(例如,//* 匹配文档中的所有元素):

Below is an example. You didn't provide any sample XML, so I kept it very generic(e.g. //* matches for all elements in the doc):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"><xsl:output method="xml"/>
<xsl:key name="names" match="//*" use="local-name(.)"/>
<xsl:template match="/">
    <xsl:for-each select="//*[generate-id(.) = generate-id(key('names', local-name(.)))]">
        <!--Do something with the unique list of elements-->
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

这篇关于XPath 获取唯一元素名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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