比较两个xml文件并显示差异

时间:2023-01-14 21:21:20

I am trying to compare two xml files and display the differences, if found.

我试图比较两个xml文件并显示差异,如果找到。

At the moment I am using XML Diff to find the difference.

目前我正在使用XML Diff来找到差异。

The method use

该方法使用

 private bool CheckDifferences(string originalFile, string newFile, ref string difference)
    {
       var diff = new XmlDiff
       {
           IgnoreComments = true,
           IgnorePI = true,
           IgnoreWhitespace = true,
           Algorithm = XmlDiffAlgorithm.Precise
       };

        var sw = new StringWriter();
        var writer = new XmlTextWriter(sw);
        writer.Formatting = Formatting.Indented;

        var originalReader = new XmlTextReader(new StringReader(originalFile));
        var modifiedReader = new XmlTextReader(new StringReader(newFile));
        var status = diff.Compare(originalReader, modifiedReader, writer);

        difference = sw.ToString();
        writer.Close();
        originalReader.Close();
        modifiedReader.Close();

        return status;
    }

But difference will contains only the change, not what exactly changed.

但差异只包含变化,而不是究竟发生了什么变化。

For example what I am trying to achieve is

例如,我想要实现的是

xml1 - Original File

xml1 - 原始文件

<catalog>
   <book id="bk11">
      <author>AuthorName1</author>
   </book>
</catalog> 

xml2 - New File

xml2 - 新文件

<catalog>
   <book id="bk11">
      <author>AuthorName2</author>
   </book>
</catalog> 

So I would like to display that author is changed to AuthorName2 etc...

所以我想显示作者已更改为AuthorName2等...

The xml file structure is unknown, but both files will have the same structure.

xml文件结构未知,但两个文件的结构相同。

Also looked at the XNode.DeepEquals, but it also return whether is there any difference or not. But not what the difference is.

还查看了XNode.DeepEquals,但它也返回是否有任何区别。但不是什么区别。

Any help is appreciate

任何帮助都很感激

1 个解决方案

#1


0  

The Compare method only returns true or false but, by looking at the documentation, the differences are written, as a XML document, to the diffgram writer (which is intended for XML Patch). So you can always interpret that document and show the changes how you want.

Compare方法只返回true或false,但是通过查看文档,差异将作为XML文档写入diffgram writer(用于XML Patch)。因此,您始终可以解释该文档并显示所需的更改。

#1


0  

The Compare method only returns true or false but, by looking at the documentation, the differences are written, as a XML document, to the diffgram writer (which is intended for XML Patch). So you can always interpret that document and show the changes how you want.

Compare方法只返回true或false,但是通过查看文档,差异将作为XML文档写入diffgram writer(用于XML Patch)。因此,您始终可以解释该文档并显示所需的更改。