如何使用 XSLT 输出重复元素? [英] How to output duplicate elements using XSLT?

查看:30
本文介绍了如何使用 XSLT 输出重复元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的 xml -

I have xml which looks something like this -

<Root>
  <Fields>
    <Field name="abc" displayName="aaa" />
    <Field name="pqr" displayName="ppp" />
    <Field name="abc" displayName="aaa" />
    <Field name="xyz" displayName="zzz" />
  </Fields>
</Root>

我希望输出只包含那些具有重复 name-displayName 组合的元素,如果有的话 -

I want the output to contain only those elements which have a repeating name-displayName combination, if there are any -

<Root>
      <Fields>
        <Field name="abc" displayName="aaa" />
        <Field name="abc" displayName="aaa" />
      </Fields>
</Root>

如何使用 XSLT 执行此操作?

How can I do this using XSLT?

推荐答案

这种转变:

<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="kFieldByName" match="Field"
  use="concat(@name, '+', @displayName)"/>

 <xsl:template match=
  "Field[generate-id()
        =
         generate-id(key('kFieldByName',
                     concat(@name, '+', @displayName)
                     )[2])
        ]
  ">
     <xsl:copy-of select=
     "key('kFieldByName',concat(@name, '+', @displayName))"/>
 </xsl:template>
</xsl:stylesheet>

应用于提供的 XML 文档时:

<Root>
    <Fields>
        <Field name="abc" displayName="aaa" />
        <Field name="pqr" displayName="ppp" />
        <Field name="abc" displayName="aaa" />
        <Field name="xyz" displayName="zzz" />
    </Fields>
</Root>

产生想要的结果:

<Field name="abc" displayName="aaa"/>
<Field name="abc" displayName="aaa"/>

说明:

  1. 慕尼黑分组使用复合键(在 namedisplayName 属性上).

代码中的唯一模板匹配其相应组中的第二个 Field 元素.然后,在模板的主体内部,输出整个组.

The only template in the code matches any Field element that is the second in its corresponding group. Then, inside the body of the template, the whole group is output.

Muenchian 分组是 在 XSLT 1.0 中进行分组的有效方法.密钥用于提高效率.

Muenchian grouping is the efficient way to do grouping in XSLT 1.0. Keys are used for efficiency.

另见我对这个问题.

See also my answer to this question.

二.XSLT 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:for-each-group select="/*/*/Field"
          group-by="concat(@name, '+', @displayName)">
       <xsl:sequence select="current-group()[current-group()[2]]"/>
   </xsl:for-each-group>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于提供的 XML 文档(如上所示)时,再次生成所需的正确结果:

<Field name="abc" displayName="aaa"/>
<Field name="abc" displayName="aaa"/>

说明:

  1. 使用<xsl:for-each-group>

current-group() 函数.

这篇关于如何使用 XSLT 输出重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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