>我正在寻找一种解决方案,从不基于确切节点名称的XML文件中删除所有重复项,相反,我正在寻找一种可以识别所有重复节点并将其删除的解决方案。只有第一个节点应该存在,其余的重复节点应该被删除。
我读了几篇类似的帖子:
XSL - 删除重复节点,但保留原始节点
使用 XSLT 删除重复元素
例:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<projects>
<project id="staticproperties">
<property name="prop1">removing this prop if its duplicate</property>
<property name="prop2">removing this prop if its duplicate</property>
<property name="prop3">removing this prop if its duplicate</property>
<property name="prop4">removing this prop if its duplicate</property>
</project>
<project id="febrelease2013">
<property name="prop">testing prop from pom.xml</property>
<property name="prop1">removing this prop if its duplicate</property>
<property name="prop3">removing this prop if its duplicate</property>
<property name="prop1">removing this prop if its duplicate</property>
<property name="prop5">removing this prop if its duplicate</property>
</project>
</projects>
注:<property name="**could be any thing**">
期望的输出是:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<projects>
<project id="staticproperties">
<property name="prop1">removing this prop if its duplicate</property>
<property name="prop2">removing this prop if its duplicate</property>
<property name="prop3">removing this prop if its duplicate</property>
<property name="prop4">removing this prop if its duplicate</property>
</project>
<project id="febrelease2013">
<property name="prop">testing prop from pom.xml</property>
<property name="prop5">removing this prop if its duplicate</property>
</project>
</projects>
通过 XSLT 1.0 执行此操作的一种方法是利用 Muenchian 分组方法仅输出唯一的<property>
元素(基于其@name
属性(。
例如,当此 XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output omit-xml-declaration="no" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="kPropertyByName" match="property" use="@name"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template
match="property[
not(
generate-id() =
generate-id(key('kPropertyByName', @name)[1])
)
]"/>
</xsl:stylesheet>
。针对提供的 XML 应用,生成所需的结果:
<?xml version="1.0" encoding="UTF-8"?>
<projects>
<project id="staticproperties">
<property name="prop1">removing this prop if its duplicate</property>
<property name="prop2">removing this prop if its duplicate</property>
<property name="prop3">removing this prop if its duplicate</property>
<property name="prop4">removing this prop if its duplicate</property>
</project>
<project id="febrelease2013">
<property name="prop">testing prop from pom.xml</property>
<property name="prop5">removing this prop if its duplicate</property>
</project>
</projects>