繁体   English   中英

Linq To Xml Null检查属性

[英]Linq To Xml Null Checking of attributes

<books>
   <book name="Christmas Cheer" price="10" />
   <book name="Holiday Season" price="12" />
   <book name="Eggnog Fun" price="5" special="Half Off" />
</books>

我想用linq解析它,我很好奇其他人用什么方法处理特殊问题。 我目前的工作方式是:

var books = from book in booksXml.Descendants("book")
                        let Name = book.Attribute("name") ?? new XAttribute("name", string.Empty)
                        let Price = book.Attribute("price") ?? new XAttribute("price", 0)
                        let Special = book.Attribute("special") ?? new XAttribute("special", string.Empty)
                        select new
                                   {
                                       Name = Name.Value,
                                       Price = Convert.ToInt32(Price.Value),
                                       Special = Special.Value
                                   };

我想知道是否有更好的方法来解决这个问题。

谢谢,

  • 贾里德

您可以将属性强制转换为string 如果它不存在,你将得到null ,后续代码应该检查null ,否则它将直接返回值。

试试这个:

var books = from book in booksXml.Descendants("book")
            select new
            {
                Name = (string)book.Attribute("name"),
                Price = (string)book.Attribute("price"),
                Special = (string)book.Attribute("special")
            };

如何使用扩展方法封装缺少的属性案例:

public static class XmlExtensions
{
    public static T AttributeValueOrDefault<T>(this XElement element, string attributeName, T defaultValue)
    {
        var attribute = element.Attribute(attributeName);
        if (attribute != null && attribute.Value != null)
        {
            return (T)Convert.ChangeType(attribute.Value, typeof(T));
        }

        return defaultValue;
    }
}

请注意,这只有在T是字符串知道通过IConvertible转换的类型时才有效。 如果您想支持更多常规转换案例,您可能还需要查找TypeConverter。 如果类型无法转换,这将抛出异常。 如果您希望这些情况也返回默认值,则需要执行其他错误处理。

在C#6.0中,您可以使用monadic Null-conditional运算符?. 在您的示例中应用它之后,它将如下所示:

var books = from book in booksXml.Descendants("book")
            select new
            {
                Name = book.Attribute("name")?.Value ?? String.Empty,
                Price = Convert.ToInt32(book.Attribute("price")?.Value ?? "0"),
                Special = book.Attribute("special")?.Value ?? String.Empty
            };

您可以在这里阅读更多部分标题为Null-conditional运算符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM