首页 > 解决方案 > 使用 xslt 从 xml 文件中删除基于条件的重复记录

问题描述

如果输入 xml 中出现重复Emplid的记录,那么我想删除状态为“已撤回”的记录。如果具有相同 emplid 的记录出现两次,我只想保留状态为活动的记录。

输入xml

<Recordset>
<Record>
    <Emplid>10001</Emplid>
    <name>Bob Dylan</name>
    <country>USA</country>
    <company>Columbia</company>
    <status>active</status>
    <year>1985</year>
</Record>
<Record>
    <Emplid>10002</Emplid>
    <name>Bonnie Tyler</name>
    <country>UK</country>
    <company>CBS Records</company>
    <status>withdrawn</status>
    <year>1988</year>
</Record>
<Record>
    <Emplid>10001</Emplid>
    <name>Bob Dylan</name>
    <country>Uk</country>
    <company>CBS Records</company>
    <status>withdrwan</status>
    <year>1975</year>
</Record>
</Recordset>

预期的 xml

Recordset>
<Record>
    <Emplid>10001</Emplid>
    <name>Bob Dylan</name>
    <country>USA</country>
    <company>Columbia</company>
    <status>active</status>
    <year>1985</year>
</Record>
<Record>
    <Emplid>10002</Emplid>
    <name>Bonnie Tyler</name>
    <country>UK</country>
    <company>CBS Records</company>
    <status>withdrawn</status>
    <year>1988</year>
</Record>
</Recordset>

感谢有人可以帮助我。

标签: xmlxslt

解决方案


所以基本上你想复制所有活动记录,以及任何没有具有相同 Emplid 的活动记录的撤回记录?

对,就是这样

那么,为什么不这样做:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="act" match="Record[status='active']" use="Emplid" />

<xsl:template match="/Recordset">
    <xsl:copy>
        <xsl:copy-of select="Record[status='active']"/>
        <xsl:copy-of select="Record[status='withdrawn'][not(key('act', Emplid))]"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

如果要保持原来的顺序,可以将两条xsl:copy-of指令合二为一:

        <xsl:copy-of select="Record[status='active'] | Record[status='withdrawn'][not(key('act', Emplid))]"/>

请注意使用来解决交叉引用。


推荐阅读