【问题标题】:Return Elements that are not in the other XML返回不在其他 XML 中的元素
【发布时间】:2012-04-06 00:27:04
【问题描述】:

我有 2 个 XElement。每个包含多个子元素

例如

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 中的所有值 我是否认为我可以通过单个查询来做到这一点,或者我必须从两者中获取结果,然后遍历它们以获取 Xml1 中不在 Xml2 中的地址??

任何帮助将不胜感激:)

【问题讨论】:

  • 看看 LINQ 'Except' 运算符
  • 鉴于错误的|| 和/或错误的where,我认为您的代码当前无法编译。
  • @paul:我相信他会想要Intersect
  • @paul 这值得指出为已回答的问题。

标签: c# xml linq


【解决方案1】:

您需要执行一个子查询 - 返回 Xml1 中 Xml2 中的所有元素 - 然后找到 Xml1 中不在子查询中的所有元素。

【讨论】:

    【解决方案2】:

    您可以通过一些匿名查询让生活更轻松:

    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);
    

    【讨论】:

      【解决方案3】:

      感谢保罗提供的信息!

      下面是适合我使用“除外”运算符的解决方案的代码

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-06
        • 1970-01-01
        • 1970-01-01
        • 2015-11-03
        • 1970-01-01
        • 1970-01-01
        • 2015-04-26
        • 1970-01-01
        相关资源
        最近更新 更多