Comparing two xml files using xslt

隐身守侯 提交于 2021-02-05 07:40:44

问题


I have two XML files :

File "a":

<?xml version="1.0"?>
 <catalog>
  <cd>d</cd>
  <cd>e</cd>
  <cd>f</cd>
  <cd>c</cd>
</catalog>

File "b":

<?xml version="1.0"?>
<catalog>
  <cd>a</cd>
  <cd>b</cd>
  <cd>c</cd>
</catalog>

I want to compare File b against File a and get those records which are only present in file b.

i.e. Expected output is :

<?xml version="1.0"?>
 <catalog>
  <cd>a</cd>
  <cd>b</cd>
</catalog>

回答1:


If you can use XSLT 2.0, then this can be done very simply (and efficiently) by using a key. Assuming you are processing the "b" file:

XSLT 2.0

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:key name="cd" match="cd" use="." />

<xsl:template match="/catalog">
    <xsl:copy>
        <xsl:copy-of select="cd[not(key('cd', ., document('a.xml')))]"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>



回答2:


A simple solution can be as follows:

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

    <xsl:template match="*">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="cd">
        <xsl:if test="not(document($compareWith)//cd = .)">
            <xsl:copy>
                <xsl:apply-templates/>
            </xsl:copy>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

The main point is that we check whether the actual cd content is not present in the document that is to be compared ($compareWith)



来源:https://stackoverflow.com/questions/29695700/comparing-two-xml-files-using-xslt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!