比较2个xml文件的数据并输出差异 [英] Compare data of 2 xml files and output the difference

查看:47
本文介绍了比较2个xml文件的数据并输出差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个具有相同架构的 xml 文件,我想比较这两个文件以仅获取出现在第一个文档中但不在第二个文档中的节点,反之亦然.

I have 2 xml files with same schema and I want to compare both the files to get only nodes which are present in 1st document but not in 2nd document and vise versa.

情况 1:

所以我的第一个 xml 是 a.xml

so my 1st xml is a.xml

<cases>
    <no sort="1">1</no>
    <no sort="2">2</no>
    <no sort="3">3</no>
    <no sort="4">4</no>
    <no sort="5">5</no>
    <no sort="6">6</no> 
</cases>

第二个 xml 是 b.xml

2nd xml is b.xml

<cases>
    <no sort="1">1</no>
    <no sort="2">2</no>
    <no sort="3">3</no>
    <no sort="4">4</no>
    <no sort="5">5</no>
    <no sort="6">6</no>
     <no sort="7">9</no>
 </cases>

比较后的预期结果应该是

Expected result after comparison should be

<cases>
       <no sort="7">9</no>
 </cases>

如果 <no sort="7">9</no> 在 a.xml 中而不是在 b.xml 中,它应该输出相同的结果.所以基本上合并两个文档并删除两个文档中存在的节点.

if <no sort="7">9</no> is in the a.xml and not in b.xml it should output the same result. So basically merging both document and remove nodes which are present in both documents.

我想一个接一个地遍历文档并使用 xpath 来检查节点是否存在是其他文档,如果发现则将其丢弃在输出中.在 xslt 1.0 或 xslt 2.0 中实现它的更好解决方案是什么?

I was thinking to loop through documents one by one and use xpath to check if the node is present is other document and if found discard it in the output. Any better solution to implement it in xslt 1.0 or xslt 2.0?

推荐答案

这种方式怎么样(XSLT 1.0):

How about this way (XSLT 1.0):

<?xml version="1.0" encoding="utf-8"?>
<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:variable name="file2" select="document('b.xml')" />

<xsl:variable name="IDs1" select="/cases/no/@sort" />
<xsl:variable name="IDs2" select="$file2/cases/no/@sort" />

<xsl:template match="/cases">
<cases>
    <xsl:apply-templates select="no[not(@sort=$IDs2)]"/>
    <xsl:apply-templates select="$file2/cases/no[not(@sort=$IDs1)]"/>
</cases>
</xsl:template>

<xsl:template match="no">
    <xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>

您需要将样式表应用到您的a.xml"文件并确保b.xml"在同一目录中.

You need to apply the stylesheet to your "a.xml " file and make sure "b.xml " is in the same directory.

这篇关于比较2个xml文件的数据并输出差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆