2011-05-10 166 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()); 

希望幫助:)