如何在 C# 中检查两个 XML 文件是否相同?
我想忽略 XML 文件中的注释。
从 NuGet安装免费的XMLDiffMerge 包。这个包本质上是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).")
}