[英]Check if two XML files are the same in C#?
如何檢查C#中的兩個XML文件是否相同?
我想忽略XML文件中的注釋。
從NuGet安裝免費的XMLDiffMerge包 。 該軟件包本質上是Microsoft的XML Diff和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).")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.