首页 > 解决方案 > XSL 1.0 替换值,然后从 xml 变量中删除重复项

问题描述

如果这是重复的,我很抱歉,但我正在努力解决这个问题。我有一个 xml 变量。我有 xsl 变量,它有这样的 xml:

<root>
    <data>
        <GroupItems>
            <row id="30" class="A100"/>

            <row id="50" class="B100"/>

            <row id="100" class="A100"/>

            <row id="20" class="C100"/>

        </GroupItems>
    </data>
</root>

我必须根据“类”值从前面的兄弟节点中替换“id”值。必须删除前面的重复 class="A100" 但必须将“id”值复制到第一个出现节点。在这种情况下,所需的输出是:

<root>
    <data>
        <GroupItems>
            <row id="100" class="A100"/>

            <row id="50" class="B100"/>

            <row id="20" class="C100"/>

        </GroupItems>
    </data>
</root>

下面的代码从字符串中删除重复项,但我需要替换 id 值(id="100")。

 <xsl:for-each select="CSharp:NodeList($RawInstruction1)//GroupItems/row[(@class = preceding-sibling::row/@class)]">

标签: c#xmlxslt

解决方案


从身份转换模板开始,然后添加一个键以row按属性“分组”元素class,然后添加模板以将id属性从row每个组中的最后一个复制到第一个,并添加另一个模板以禁止复制 a 中剩余的重复rows团体:

<?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"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:key name="class-group" match="GroupItems/row" use="@class"/>

  <xsl:template match="GroupItems/row[generate-id() = generate-id(key('class-group', @class)[1])]/@id">
      <xsl:copy-of select="key('class-group', ../@class)[last()]/@id"/>
  </xsl:template>

  <xsl:template match="GroupItems/row[not(generate-id() = generate-id(key('class-group', @class)[1]))]"/>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/nc4NzRn


推荐阅读