【问题标题】:XSLT Checking duplicate values in whole XMLXSLT 检查整个 XML 中的重复值
【发布时间】:2020-05-20 15:51:49
【问题描述】:

我有一个这样的 XML:

<items>
 <item>
  <attribute>1</attribute>
 </item>
 <item>
  <attribute>2</attribute>
 </item>
 <item>
  <attribute>3</attribute>
 </item>
 <item>
  <attribute>2</attribute>
 </item>
 <item>
  <attribute>1</attribute>
 </item>
 <item>
  <attribute>1</attribute>
 </item>
 <item>
  <attribute>4</attribute>
 </item>
</items>

我需要一个 XSLT 来生成这个输出:

<items>
 <item>
  <attribute>1</attribute>
 </item>
 <item>
  <attribute>2</attribute>
 </item>
 <item>
  <attribute></attribute>
 </item>
 <item>
  <attribute>2</attribute>
 </item>
 <item>
  <attribute>1</attribute>
 </item>
 <item>
  <attribute>1</attribute>
 </item>
 <item>
  <attribute></attribute>
 </item>
</items>

基本上,我希望 XSLT 仅在整个文件中至少出现两次时才显示值。我只能用 XSLT 1.0 来做,这可能吗?

【问题讨论】:

    标签: xml xslt xslt-1.0


    【解决方案1】:

    您可以使用以下方法获得问题中显示的输出:

    XSLT 1.0

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>
    
    <xsl:key name="att" match="attribute" use="." />
    
    <!-- identity transform -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="attribute[count(key('att', .)) = 1]">
        <xsl:copy/>
    </xsl:template>
    
    </xsl:stylesheet>
    

    【讨论】:

    • 有趣的答案。我试图理解“count(key('att', .)) = 1”谓词。本能地我会使用> 1,但你的解决方案有效。您能否解释一下为什么当键中有多个此元素时 count=1 ?谢谢。
    • @Sebastien 规则是复制元素as is。这由身份转换模板处理。例外是只复制元素,而不是它的值。此例外适用于其值仅出现一次的元素。因此,只有至少出现两次的值才会被复制。
    猜你喜欢
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 2021-10-17
    相关资源
    最近更新 更多