XPath最后一次出现的每个元素

时间:2011-07-05 09:57:44

标签: xml xslt xpath

我喜欢XML

<root>
    <a>One</a>
    <a>Two</a>
    <b>Three</b>
    <c>Four</c>
    <a>Five</a>
    <b>
        <a>Six</a>
    </b>
</root>

并且需要选择root中任何子节点名称的最后一次出现。在这种情况下,所需的结果列表将是:

<c>Four</c>
<a>Five</a>
<b>
    <a>Six</a>
</b>

感谢任何帮助!

4 个答案:

答案 0 :(得分:6)

XPath 2.0解决方案和当前接受的答案效率都非常低(O(N ^ 2))。

此解决方案具有次线性复杂性:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:key name="kElemsByName" match="/*/*"
  use="name()"/>

 <xsl:template match="/">
  <xsl:copy-of select=
    "/*/*[generate-id()
         =
          generate-id(key('kElemsByName', name())[last()])
         ]"/>
 </xsl:template>
</xsl:stylesheet>

应用于提供的XML文档

<root>
    <a>One</a>
    <a>Two</a>
    <b>Three</b>
    <c>Four</c>
    <a>Five</a>
    <b>
        <a>Six</a>
    </b>
</root>

产生了想要的正确结果

<c>Four</c>
<a>Five</a>
<b>
   <a>Six</a>
</b>

解释:这是Muenchian grouping的修改变体 - 所以不是第一个。但是处理了每个组中的最后一个节点。

II XPath 2.0 one-liner

使用:

/*/*[index-of(/*/*/name(), name())[last()]]

使用XSLT 2.0作为XPath 2.0主机进行验证

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  <xsl:sequence select=
    "/*/*[index-of(/*/*/name(), name())[last()]]"/>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于同一XML文档(前面提供)时,会产生相同的正确结果

<c>Four</c>
<a>Five</a>
<b>
    <a>Six</a>
</b>

答案 1 :(得分:4)

如果你能使用XPath 2.0,那么

/root//*[not(name() = following-sibling::*/name())]

答案 2 :(得分:3)

基于XSLT的解决方案:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="root/*">
        <xsl:variable name="n" select="name()"/>
        <xsl:copy-of
            select=".[not(following-sibling::node()[name()=$n])]"/>
    </xsl:template>
</xsl:stylesheet>

产生输出:

<c>Four</c>
<a>Five</a>
<b>
   <a>Six</a>
</b>

第二个解决方案(您可以将其用作单个XPath表达式):

<xsl:template match="/root">
    <xsl:copy-of select="a[not(./following-sibling::a)]
        | b[not(./following-sibling::b)]
        | c[not(./following-sibling::c)]"/>
</xsl:template>

答案 3 :(得分:0)

如今, XSLT 2.0 为这类问题提供了grouping techniques

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes" />
    <xsl:strip-space elements="*" />

    <xsl:template match="/root">
        <xsl:for-each-group select="*" group-by="name()">
            <!-- <xsl:sort select="index-of(/root/*, current-group()[last()])" order="ascending"/> -->
            <xsl:copy-of select="current-group()[last()]" />
        </xsl:for-each-group>
    </xsl:template>
</xsl:stylesheet>

将产生:

<a>Five</a>
<b>
  <a>Six</a>
</b>
<c>Four</c>

除非明确受<xsl:sort>

的影响,否则按文档顺序进行分组