【问题标题】:Using XDocument.Descendants with a coalesce operator ?? and nullable types将 XDocument.Descendants 与合并运算符一起使用??和可为空的类型
【发布时间】:2021-12-21 09:24:18
【问题描述】:

编译器:Visual Studio 2019
框架:.Net 2.1

给定一个这样的 XML 文件:

<root>
  <data>
        <AdditionalOrderInfo>
            <AdditionalInfoItem key="{4567B566-A0A2-4214-B7E7-814FE179CDFC}" value="ScanItDental"/>
            <AdditionalInfoItem key="GlobalOrderID" value="EDC531BE6A0D4DC5BFEA0C6081D9F26B"/>
            <AdditionalInfoItem key="CreatedIn" value="2.20.1.2"/>
        </AdditionalOrderInfo>  
    </data>
</root>

我只需要为某些key 值获取AdditionalInfoItem

为了避免空错误,我尝试使用可空类型和合并运算符??

var additionalOrderInfo = document.Descendants(ns + "AdditionalOrderInfo").First();
var value = additionalOrderInfo.Descendants(ns + "AdditionalInfoItem")?.Where(el => el.Attribute("key").Value == "SomeKey")?.First()?.Attribute("value")?.Value ?? "";

但如果key 不存在,它会返回:

序列不包含任何元素。

我已经以这种方式结束了使用foreach 循环:

var additionalOrderInfo = document.Descendants(ns + "AdditionalOrderInfo").First();
foreach (var item in additionalOrderInfo.Descendants(ns + "AdditionalInfoItem"))
{
    switch (item.Attribute("key").Value)
    {
        case "SomeKey1":
            Order.SomeKey1 = item.Attribute("value").Value;
            break;
        case "SomeKey2":
            Order.SomeKey2 = item.Attribute("value").Value;
            break;
    }
}

有没有办法避免foreach 循环并使用一行代码读取值?

【问题讨论】:

  • 如果我理解正确,如果additionalOrderInfonull,为什么还需要foreach? IOW,如果没有 orderinfo,为什么会有项目循环进入?

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


【解决方案1】:

仅在Where 选择器之后尝试使用FirstOrDefault 而不是First

var value = additionalOrderInfo.Descendants(ns + "AdditionalInfoItem")?
                               .Where(el => el.Attribute("key").Value == "SomeKey")?
                               .FirstOrDefault()? // <--- Here
                               .Attribute("value")?.Value ?? "";

如果Where(el =&gt; el?.Attribute("key")?.Value == "SomeKey")返回0个元素,你得到Sequence contains no elements异常,所以你不能得到它的First元素。 FirstOrDefault 改为返回 null,因此下一个 nullcheck ? 继续进行。

【讨论】:

  • 谢谢,它有效,
猜你喜欢
  • 2017-11-24
  • 2011-12-24
  • 1970-01-01
  • 2017-11-23
  • 2014-08-06
  • 2012-04-27
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
相关资源
最近更新 更多