检查C#中的两个XML文件是否相同?

时间:2013-11-13 12:40:52

标签: c# .net xml

如何检查C#中的两个XML文件是否相同?

我想忽略XML文件中的注释。

1 个答案:

答案 0 :(得分:6)

安装免费XMLDiffMerge package from NuGet。该软件包本质上是Microsoft的XML Diff and Patch GUI Tool的重新打包版本。

如果两个XML文件相同,则此函数返回true,忽略注释,空格和子顺序。作为奖励,它还可以解决差异(请参阅函数中的内部变量differences)。

/// <summary>
/// Compares two XML files to see if they are the same.
/// </summary>
/// <returns>Returns true if two XML files are functionally identical, ignoring comments, white space, and child
/// order.</returns>
public static bool XMLfilesIdentical(string originalFile, string finalFile)
{
    var xmldiff = new XmlDiff();
    var r1 = XmlReader.Create(new StringReader(originalFile));
    var r2 = XmlReader.Create(new StringReader(finalFile));
    var sw = new StringWriter();
    var xw = new XmlTextWriter(sw) { Formatting = Formatting.Indented };

    xmldiff.Options = XmlDiffOptions.IgnorePI | 
        XmlDiffOptions.IgnoreChildOrder | 
        XmlDiffOptions.IgnoreComments |
        XmlDiffOptions.IgnoreWhitespace;
    bool areIdentical = xmldiff.Compare(r1, r2, xw);

    string differences = sw.ToString();

    return areIdentical;
}   

以下是我们如何调用该函数:

string textLocal = File.ReadAllText(@"C:\file1.xml");
string textRemote = File.ReadAllText(@"C:\file2.xml");
if (XMLfilesIdentical(textLocal, textRemote) == true)
{
    Console.WriteLine("XML files are functionally identical (ignoring comments).")
}