2011-05-10 164 views
1

如何比较来自C#中两个不同xml文件的元素?只有元素名称必须与元素值进行比较。xml元素比较

我使用:

XDocument file1 = XDocument.Load(dest_filename); 
XDocument file2 = XDocument.Load(source_filename); 

if (file1.Nodes().Intersect(file2.Nodes()).Count() > 0) 
{ 
    MessageBox.Show("hey i popped up"); 
} 

但比较值太大,我不希望比较..

回答

0

鉴于file1.xml:

<root> 
    <a></a> 
    <b></b> 
    <c></c> 
</root> 

和file2.xml:

<root> 
    <a></a> 
    <b></b> 
    <b></b> 
    <c></c> 
    <d></d> 
</root> 

下面的代码将生成四个消息框(为节点A,B,b和c)

XDocument doc = XDocument.Load(System.IO.Path.GetFullPath("file1.xml")); 
XDocument doc2 = XDocument.Load(System.IO.Path.GetFullPath("file2.xml")); 

var matches = from a in doc.Element("root").Descendants() 
      join b in doc2.Element("root").Descendants() on a.Name equals b.Name 
      select new { First = a, Second = b }; 

foreach (var n in matches) 
    MessageBox.Show(n.First.ToString() + " matches " + n.Second.ToString()); 

希望帮助:)