我正在尝试编写一个简单的算法,用于读取两个XML文件,这两个文件具有相同的节点和结构,但子节点中的数据不一定相同,且顺序也可能不同。我应该如何使用Microsoft的XML Diff .DLL创建一个简单的实现来创建第三个临时XML,该XML是前两个XML之间的差异呢?
MSDN上的XML Diff: XML Diff and Patch Tool XML Diff and Patch GUI Tool 要比较的两个不同的XML文件的示例XML代码:
目前我拥有的C#代码:
MSDN上的XML Diff: XML Diff and Patch Tool XML Diff and Patch GUI Tool 要比较的两个不同的XML文件的示例XML代码:
<?xml version="1.0" encoding="utf-8" ?>
<Stats Date="2011-01-01">
<Player Rank="1">
<Name>Sidney Crosby</Name>
<Team>PIT</Team>
<Pos>C</Pos>
<GP>39</GP>
<G>32</G>
<A>33</A>
<PlusMinus>20</PlusMinus>
<PIM>29</PIM>
</Player>
</Stats>
<?xml version="1.0" encoding="utf-8" ?>
<Stats Date="2011-01-10">
<Player Rank="1">
<Name>Sidney Crosby</Name>
<Team>PIT</Team>
<Pos>C</Pos>
<GP>42</GP>
<G>35</G>
<A>34</A>
<PlusMinus>22</PlusMinus>
<PIM>30</PIM>
</Player>
</Stats>
期望的结果(两者之间的差异)
<?xml version="1.0" encoding="utf-8" ?>
<Stats Date="2011-01-10">
<Player Rank="1">
<Name>Sidney Crosby</Name>
<Team>PIT</Team>
<Pos>C</Pos>
<GP>3</GP>
<G>3</G>
<A>1</A>
<PlusMinus>2</PlusMinus>
<PIM>1</PIM>
</Player>
</Stats>
在这种情况下,我可能会使用XSLT将生成的XML“差异”文件转换为排序的HTML文件,但我还没有做到。我想要做的就是在第三个XML文件中显示每个节点从“GP”子节点开始的每个数值差异。目前我拥有的C#代码:
private void CompareXml(string file1, string file2)
{
XmlReader reader1 = XmlReader.Create(new StringReader(file1));
XmlReader reader2 = XmlReader.Create(new StringReader(file2));
string diffFile = StatsFile.XmlDiffFilename;
StringBuilder differenceStringBuilder = new StringBuilder();
FileStream fs = new FileStream(diffFile, FileMode.Create);
XmlWriter diffGramWriter = XmlWriter.Create(fs);
XmlDiff xmldiff = new XmlDiff(XmlDiffOptions.IgnoreChildOrder |
XmlDiffOptions.IgnoreNamespaces |
XmlDiffOptions.IgnorePrefixes);
bool bIdentical = xmldiff.Compare(file1, file2, false, diffGramWriter);
diffGramWriter.Close();
// cleaning up after we are done with the xml diff file
File.Delete(diffFile);
}
这是我目前的代码,但结果很糟糕...请注意,对于每个“Player”节点,前三个子节点不需要进行比较...我该如何实现这一点?