【问题标题】:How to conditionally read elements in LINQToXML如何有条件地读取 LINQ To XML 中的元素
【发布时间】:2016-02-10 18:50:14
【问题描述】:

如何使用 LINQToXml 创建我想要的列表? 到目前为止,我对这两种尝试都很接近。
我应该能够做到这一点而无需创建单独的查询,对吗?

这是我的 XML:

<main>
  <cars>
    <car name="Honda">
      <feature door="4" name="Accord" />
      <feature door="2" name="Civic"/>
      <feature door="4" name="CRV"/>
    </car>
    <car name="Ford"/>
    <car name="Kia"/>
    <car name="Subaru">
      <feature door="4" name="Outback"/>
      <feature door="4" name="Legacy"/>
    </car>
  </cars>
</main>

尝试 #1

  • 这将返回第一辆具有功能的汽车。
    var listCars = (from c in doc.Root.Descendants("cars")
    select new Car
    {
       Model = (p.Element("car") != null) ? p.Element("car").Attribute("name").Value : null,
       Door = (p.Element("car") != null) ? p.Element("car").Attribute("door").Value : null,
       Name = p.Attribute("name").Value
    }).ToList();
    

    尝试 #2

  • 这将返回所有具有功能的汽车
  • 福特和起亚将失踪
    var cars = from c in doc.Root.Descendants("cars")
    select c;
    
    var listPermissions = (from c in cars.Descendants("car")
    let cName = p.Parent.Attribute("name").Value
    select new Car
    {
      Model = p.Attribute("name").Value,
      Door = p.Attribute("door").Value,
      Name = pgn
    }).ToList();
    

    我要做的是创建一个看起来像这样的汽车列表:

  • 本田,4,雅阁
  • 本田,2,思域
  • 本田,4,CRV
  • 福特,空,空
  • 起亚,空,空
  • 斯巴鲁,4,内陆
  • 斯巴鲁,4,力狮
  • 【问题讨论】:

    • Car 包含门和名称列表不是更容易吗?而不是尝试将其全部展平?

    标签: linq c#-4.0 linq-to-xml


    【解决方案1】:

    您可以通过在 LINQ 中使用 LEFT JOIN 来完成此操作,如 101 LINQ Samples 所述。

    var makes =
        (from doc in document.Root.Descendants("cars").Descendants("car")
         join f in document.Root.Descendants("cars").Descendants("car").Descendants("feature") 
           on doc.Attribute("name").Value.ToLowerInvariant() equals f.Parent.Attribute("name").Value.ToLowerInvariant() into ps
         from f in ps.DefaultIfEmpty()
       select new
            {
                Model = doc.Attribute("name").Value,
                Door = f == null ? string.Empty : f.Attribute("door").Value,
                Name = f == null ? string.Empty : f.Attribute("name").Value
            })
        .ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      相关资源
      最近更新 更多