代码之家  ›  专栏  ›  技术社区  ›  Retrocoder

通过Linq获取XML值时设置默认值

  •  1
  • Retrocoder  · 技术社区  · 14 年前

    我使用Linq从一些XML中提取值。下面是一个简单的例子来说明我的问题。下面的代码在如下所示的XML上运行良好。我的问题是 groupBy 节丢失。因为它不见了 Data.Element("groupBy").Element("property) Data.Element("groupBy")

    var e = (from Data in theXML.Descendants("exportFile")
     select new Export
     {    
         OutputFileName = Data.Element("outputFileName") != null ? (string)Data.Element("outputFileName") : "",
         GroupByProperty =  Data.Element("groupBy").Element("property") != null ? (string)Data.Element("groupBy").Element("property") : ""
     }).First();
    

    <exportFile>
        <outputFileName>output.xml</outputFileName>
        <groupBy>
            <property>DeviceId</property>
        </groupBy>
    </exportFile>
    
    2 回复  |  直到 11 年前
        1
  •  3
  •   Jon Skeet    14 年前

    您已经可以使它比使用空合并操作符稍微好一些。然而,为了应对 groupby 缺少元素更难:

    select new Export
    {    
        OutputFileName = (string) Data.Element("outputFileName") ?? "",
        GroupByProperty = Data.Element("groupBy") == null ? ""
               : (string) Data.Element("groupBy").Element("property") ?? ""
    }).First();
    

    如果元素引用为null,则转换为字符串只返回null。

    GroupByProperty = 
        (string) Data.Elements("groupBy").Elements("property").FirstOrDefault() ?? ""
    

    它使用扩展方法,该方法允许您调用 Elements IEnumerable<XElement> ... 所以这将(懒散地)评估每个 property groupBy 下的元素 Data

        2
  •  0
  •   Justin Niessner    14 年前

    您可以简单地在语句中添加一个附加的检查(并使用null合并操作符稍微清理一下):

    GroupByProperty = Data.Element("groupBy") != null ? 
        (Data.Element("groupBy").Element("property") ?? "") : "";