我需要帮助,我有两个XML文件,它们具有相同的id(“ name”),我希望两者之间有所不同。 如果我在Xml file_1中有多余的节点,那么它将转到diff。仅根据ID的xml文件。 我已经编写了som代码,但我不知道如果怎么做;我知道我们可以在Microsoft Diff and Patch工具中执行操作,但是我想要一个不同的代码: 这是我的代码:
public static void Main()
{
//fields
const string XML1 = @"File_1.xml";
const string XML2 = @"File_2.xml";
const string ResultFile = @"ResultFile.xml";
XmlDocument doc1 = new XmlDocument();
doc1.Load(XML1);
XmlDocument doc2 = new XmlDocument();
doc2.Load(XML2);
for(var d = 0; d < doc1.SelectNodes("root/data").Count; d++)
{
var child = doc1.SelectNodes("root/data")[d];
if (I don't know …..) {
}
}
XML fil_1
<root>
<data name="senChangePassword" xml:space="preserve">
<value>Byt lösenord</value>
<comment>Sprint 02 - Jessica</comment>
</data>
<data name="senChangesWereSuccessfullySaved" xml:space="preserve">
<value>Ändringarna är sparade</value>
<comment>Sprint 02 - Jessica</comment>
</data>
<data name="senChangeUserSettings" xml:space="preserve">
<value>Ändra uppgifter</value>
<comment>Sprint 02 - Jessica</comment>
</data>
<data name="senCompareWith" xml:space="preserve">
<value>Jämför</value>
<comment>Sprint 02 - Jessica</comment>
</data>
<data name="senCreatedQuestions" xml:space="preserve">
<value>Skapade frågor</value>
<comment>Sprint 02 - Jessica</comment>
</data>
</root>
** XML文件_2 **
<root>
<data name="senChangePassword" xml:space="preserve">
<value>Change Password</value>
<comment>Sprint 02 - Jessica</comment>
</data>
<data name="senChangesWereSuccessfullySaved" xml:space="preserve">
<value>Saved changes</value>
<comment>Sprint 02 Jessica</comment>
</data>
<data name="senCompareWith" xml:space="preserve">
<value>Compare</value>
<comment>Sprint 02 - Jessica</comment>
</data>
</root>
XML file_result
<root>
<data name="senChangeUserSettings" xml:space="preserve">
<value>Ändra uppgifter</value>
<comment>Sprint 02 - Jessica</comment>
</data>
<data name="senCreatedQuestions" xml:space="preserve">
<value>Skapade frågor</value>
<comment>Sprint 02 - Jessica</comment>
</data>
</root>
答案 0 :(得分:1)
简单版本(如果您不关心性能或内存大小):
using System.Linq;
// ....
var nodes1 = doc1.SelectNodes("root/data");
var children1 = new List<XmlNode>();
int i = 0;
foreach(XmlNode a in nodes1) { children1[i++] = a; }
var nodes2 = doc2.SelectNodes("root/data");
var children2 = new List<XmlNode>();
i = 0;
foreach(XmlNode b in nodes2) { children2[i++] = b; }
var result = new List<XmlNode>();
for(var d = 0; d < children1.Count; d++)
{
var child = children1[d];
var match = children2.FirstOrDefault(x=>
XElement.Parse(x.OuterXml).ToString() == XElement.Parse(child.OuterXml).ToString());
if (match == null) {
result.Add(child);
}
}
将结果节点尽可能地转储到结果文件中