xml - 如果 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 提前谢谢。
解决方案
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>
推荐阅读
- javascript - 带参数的 Typeorm 监听器
- c# - ASP.NET MVC C# - 显示类属性名称而不是 JSON 中的属性名称
- python-3.x - 我如何传递字典键树作为参数来获取 4 级嵌套字典中的值?
- docker - InfluxDb 使用 docker,Ubuntu 20.04 作为本地主机上 traefik 后面的子位置
- python - 在尝试计算统计数据时获取“提供了一个或多个数据系列..”
- android - ActivityLifecycleCallbacks 不会触发
- oauth-2.0 - 使用 AzureAD 自定义 OAuth2.0 失败时的错误页面
- python - 将烧瓶表导出到 excel 并在 html 中设置样式的问题
- javascript - timeupdate 事件 - 在 addEventListener 中获取 POST 数据
- json - 在 POST 请求的 Body Flutter 中添加整个 JSON 数据