【问题标题】:Querying XML with LINQ and using null in place of a particular xml attribute if it does not exist使用 LINQ 查询 XML 并使用 null 代替特定的 xml 属性(如果它不存在)
【发布时间】:2011-12-12 10:04:03
【问题描述】:

我有一个模型类

public class Item
{
    public string Name {get; set;}
    public string Desc {get; set;}
}

我会查询我的 XML 文档

List<Item> item = xmlDoc.Descendants()
    .Select(o => new Item { 
        Name = o.Attribute("name").Value, 
        Desc = o.Attribute("desc").Value
    }).ToList(); 

但是,desc 属性可能存在也可能不存在于每个项目中。如果属性 desc 存在,则上述 LINQ 有效,但如果不存在,则会导致异常。

如果它不存在,我希望 LINQ 查询仅将 null 分配给新 Item 对象中的 Desc 字段。感谢您的任何建议。

【问题讨论】:

标签: c# xml linq


【解决方案1】:

正确的做法是使用转换运算符:

Name = (string) o.Attribute("name"),
Desc = (string) o.Attribute("desc")

为什么这是首选方式?首先,它很容易;其次,它适用于其他类型:

Count = (int?) o.Attribute("count"),
When = (DateTime?) o.Attribute("when")

特别是,它们还为每种数据类型应用正确的 xml 编码规则,而不是使用特定于文化的 DateTime.Parse / int.Parse 等。很多微妙的事情不想记住!

请注意,如果您想断言该属性存在,非Nullable&lt;T&gt; 版本也可以:

Size = (int) o.Attribute("size"),
Created = (DateTime) o.Attribute("created")

【讨论】:

    【解决方案2】:

    您可以使用三元运算符 - ?:

    List<Item> item = xmlDoc.Descendants() 
        .Select(o => new Item {  
            Name = o.Attribute("name") != null ? o.Attribute("name").Value : null,  
            Desc = o.Attribute("desc") != null ? o.Attribute("desc").Value : null,
        }).ToList();  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多