[英]How can I compare 2 XML Documents?
I have two documents both are similar but I need to find an elegant and efficient way to compare the two files and return the values in Doc #1 that don't exist in Doc #2. 我有两个文档都相似,但是我需要找到一种优雅而有效的方式来比较两个文件并返回Doc#1中不存在Doc#2中的值。
XML Doc #1 XML文件#1
<ids>
<id>1</id>
<id>2</id>
<id>5</id>
<id>6</id>
<id>7</id>
<id>8</id>
<id>9</id>
</ids>
</ids>
XML Doc #2 XML文件#2
<ids>
<id>1</id>
<id>2</id>
<id>7</id>
<id>8</id>
<id>9</id>
</ids>
I was thinking about using linq if I could join these two documents on the id field. 我在考虑使用linq是否可以在id字段上加入这两个文档。 Is there a better way? 有没有更好的办法? I'm looking to return id #s 5 and 6. 我希望返回ID 5和6。
Here is a sample that I know works, I only tried it out with small files (File1.xml had 20 items, File2.xml 8 items). 这是一个我知道有效的示例,我仅使用小文件(File1.xml有20个项目,File2.xml有8个项目)进行了尝试。
XDocument file1Doc = XDocument.Load("File1.xml");
XDocument file2Doc = XDocument.Load("File2.xml");
IEnumerable<string> file1Elements = from d in file1Doc.Descendants("Id")
select d.Value;
IEnumerable<string> file2Elements = from d in file2Doc.Descendants("Id")
select d.Value;
var difference = file1Elements.Except(file2Elements);
Alternatively, and likely more inline with what you seek is: 另外,可能更符合您的需求的是:
XDocument file1Doc = XDocument.Load("File1.xml");
XDocument file2Doc = XDocument.Load("File2.xml");
IEnumerable<string> file2Elements = from d in file2Doc.Descendants("Id")
select d.Value;
var x = from include in file1Doc.Descendants("Id")
where file2Elements.Contains(include.Value) != true
select include;
You might also find some help looking at 101 LINQ Samples on MSDN . 您还可以在MSDN上查看101 LINQ示例获得帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.