首页 > 解决方案 > 如果 id 重复,则使用 xslt 更改重复的 id

问题描述

我有一个重复 id 的 xml 输入,如下所示

<root>
<p>text 1</p>
<text id="Read-R1">
<p>sample 1</p>
</text>
<p>text 2</p>
<text id="Read-R2">
<p>sample 2</p>
</text>
<p>text 3</p>
<text id="Read-R1">
<p>sample 3</p>
</text>
<p>text 4</p>
<text id="Read-R2">
<p>sample 3</p>
</text>
<p>text 5</p>
<text id="Read-R1">
<p>sample 5</p>
</text>
<text id="Read-R3">
<p>sample 3</p>
</text>
</root>

重复的 id 我想将附加 -01 更改为重复的 id 只有第一个 id 与它相同:输出为:

<root>
<p>text 1</p>
<text id="Read-R1">
<p>sample 1</p>
</text>
<p>text 2</p>
<text id="Read-R2">
<p>sample 2</p>
</text>
<p>text 3</p>
<text id="Read-R1-01">
<p>sample 3</p>
</text>
<p>text 4</p>
<text id="Read-R2-01">
<p>sample 3</p>
</text>
<p>text 5</p>
<text id="Read-R1-02">
<p>sample 5</p>
</text>
<text id="Read-R3">
<p>sample 3</p>
</text>
</root>

请建议 xslt 为重复的 ID 附加 -01 提前谢谢。

标签: xmlxslt-2.0

解决方案


This wil work with a bonus, that if there are more then one with that same @id it still creates unique ids.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="*">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>
    
  <xsl:template match="text[@id]">
    <xsl:variable name="sId" select="@id"/>
    <xsl:variable name="iPrecedingIdsWithSameValue" select="count(preceding-sibling::text[@id=$sId])"/>
    <xsl:copy>
      <xsl:attribute name="id" select="if($iPrecedingIdsWithSameValue gt 0) then concat(@id,'-',format-number($iPrecedingIdsWithSameValue,'00')) else @id"/>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

推荐阅读