XSLT (Extensible Stylesheet Language Transformations) 是一种用于将 XML 文档转换为其他格式的语言。在处理 XML 数据时,我们经常需要去除重复的元素或节点。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<!-- 定义一个键来标识重复元素 -->
<xsl:key name="elements-by-value" match="要删除重复的节点名称" use="."/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- 只处理第一次出现的元素 -->
<xsl:template match="要删除重复的节点名称[generate-id() = generate-id(key('elements-by-value', .)[1])]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- 忽略后续出现的重复元素 -->
<xsl:template match="要删除重复的节点名称"/>
</xsl:stylesheet>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="父节点名称">
<xsl:copy>
<!-- 获取不重复的子节点值 -->
<xsl:for-each select="distinct-values(要删除重复的节点名称)">
<xsl:copy>
<xsl:value-of select="."/>
</xsl:copy>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- 只处理没有相同值的前驱兄弟节点的元素 -->
<xsl:template match="要删除重复的节点名称[not(. = preceding-sibling::要删除重复的节点名称)]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- 忽略重复元素 -->
<xsl:template match="要删除重复的节点名称"/>
</xsl:stylesheet>
假设有以下 XML:
<books>
<book id="1">XML Basics</book>
<book id="2">XSLT Guide</book>
<book id="3">XML Basics</book>
<book id="4">XPath Tutorial</book>
<book id="5">XSLT Guide</book>
</books>
使用 Muenchian 分组法的完整解决方案:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:key name="books-by-title" match="book" use="."/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="book[generate-id() = generate-id(key('books-by-title', .)[1])]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="book"/>
</xsl:stylesheet>
输出结果:
<books>
<book id="1">XML Basics</book>
<book id="2">XSLT Guide</book>
<book id="4">XPath Tutorial</book>
</books>
没有搜到相关的文章