Check if two XML files are the same in C#?

前端 未结 1 1681
生来不讨喜
生来不讨喜 2021-01-13 00:59

How do I check to see if two XML files are the same in C#?

I want to ignore comments in the XML file.

1条回答
  •  一个人的身影
    2021-01-13 01:30

    Install the free XMLDiffMerge package from NuGet. This package is essentially a repackaged version of the XML Diff and Patch GUI Tool from Microsoft.

    This function returns true if two XML files are identical, ignoring comments, white space, and child order. As a bonus, it also works out the differences (see the internal variable differences in the function).

    /// 
    /// Compares two XML files to see if they are the same.
    /// 
    /// Returns true if two XML files are functionally identical, ignoring comments, white space, and child
    /// order.
    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;
    }   
    

    Here is how we call the function:

    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).")
    }
    

    0 讨论(0)
提交回复
热议问题