2012-03-21 21 views
0

我有2個XElements。每一個包含多個兒童要件返回不在其他XML中的元素

XML1:

<Addresses> 
    <Address> 
    <Line1>1 Street</Line1> 
    <Postcode>PL1 5RT</Postcode> 
    </Address> 
    <Line1>57 New Street</Line1> 
    <Postcode>PL1 5RT</Postcode> 
    </Address> 
    <Address> 
    <Line1>2 Street</Line1> 
    <Postcode>PL1 5RT</Postcode> 
    </Address> 
</Addresses> 

XML2:

<Addresses> 
    <Address> 
    <Line1>1 Street</Line1> 
    <Postcode>PL1 5RT</Postcode> 
    </Address> 
    <Address> 
    <Line1>2 Street</Line1> 
    <Postcode>PL1 5RT</Postcode> 
    </Address> 
</Addresses> 

我試圖把一個LINQ查詢,將篩選出的地址元素在Xml中但不在Xml2中(在上述情況下,它將是地址「57 New Street」)

目前我的代碼看起來是這樣的:

var diffAddress = from address1 in Xml1.Elements() 
        from address2 in Xml2.Elements() 
        where (string)address1.Element("Line1") != (string)address2.Element("Line1") || 
        where (string)address1.Element("Postcode") != (string)address2.Element("Postcode") 
        select address1; 

然而其返回的所有值的XML1 難道我就在想,我可以通過一個單一的查詢做到這一點還是我將不得不透過這兩個結果然後遍歷它們以獲取不在Xml2中的Xml1中的地址?

任何幫助,將不勝感激:)

+3

看一看的LINQ「除」操作 – paul 2012-03-21 13:21:00

+0

我不認爲你的代碼目前彙編給出錯誤的'代碼|| '和/或錯誤'在哪裏。 – user7116 2012-03-21 14:11:23

+0

@paul:我相信他會想'交集'。 – user7116 2012-03-21 14:23:41

回答

0

感謝資訊保羅!

下面是一個適合使用我的解決方案「除了」運營商

var newAddresses= Xml1.Descendants("Address").Cast<XNode>() 
         .Except(Xml2.Descendants("Address").Cast<XNode>(), new XNodeEqualityComparer()); 
0

你需要做一個子查詢 - 返回從XML1是在XML2的所有元素 - 然後發現沒有在子查詢中XML1的所有元素。

1

可以使生活更輕鬆一些匿名查詢:

var addresses2 = from xaddr in x2.Root.Elements("Address") 
       let a = new 
         { 
          Line1 = xaddr.Element("Line1").Value, 
          PostalCode = xaddr.Element("Postcode").Value 
         } 
       select a; 

// take the addresses in the first XML which are found in the second XML 
// nota bene: this is case sensitive. 
var addresses = (from xaddr in x1.Root.Elements("Address") 
       let a = new 
         { 
          Line1 = xaddr.Element("Line1").Value, 
          PostalCode = xaddr.Element("Postcode").Value 
         } 
       select a) 
       .Intersect(addresses2);