gpt4 book ai didi

c# - 检查两个 XML 文件在 C# 中是否相同?

转载 作者:数据小太阳 更新时间:2023-10-29 01:51:01 26 4
gpt4 key购买 nike

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

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

最佳答案

安装免费 XMLDiffMerge package from NuGet .这个包本质上是 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).")
}

关于c# - 检查两个 XML 文件在 C# 中是否相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19954062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com