使用XDocument&Linq读取XML - 检查元素是否为NULL?

adc*_*sed 24 c# xml linq asp.net

我正在使用LINQ和XDocument来读取XML文件.这是代码:

XDocument xml = XDocument.Load(filename);

var q = from b in xml.Descendants("product")
        select new
        {
            name = b.Element("name").Value,
            price = b.Element("price").Value,                    
            extra = b.Element("extra1").Value,
            deeplink = b.Element("deepLink").Value                   
        };
Run Code Online (Sandbox Code Playgroud)

现在的问题是,该extra1领域并不总是存在.没有该节点的XML文件中有项目.如果发生这种情况,它会因NullReferenceException而崩溃.

有没有可能包括"检查是否为空",以便我可以防止它崩溃?

dtb*_*dtb 42

使用(string)而不是.Value:

var q = from b in xml.Descendants("product")
        select new
        {
            name = (string)b.Element("name"),
            price = (double?)b.Element("price"),                    
            extra = (string)b.Element("extra1"),
            deeplink = (string)b.Element("deepLink")                   
        };
Run Code Online (Sandbox Code Playgroud)

这也适用于其他数据类型,包括许多可空类型,以防元素不总是存在.


Mar*_*qus 8

您可以使用"null coalescing"运算符:

var q = from b in xml.Descendants("product")
        select new
        {
            name = (string)b.Element("name") ?? "Default Name",
            price = (double?)b.Element("price") ?? 0.0,                    
            extra = (string)b.Element("extra1") ?? String.Empty,
            deeplink = (string)b.Element("deepLink") ?? String.Empty                   
        };
Run Code Online (Sandbox Code Playgroud)

这样,您就可以完全控制没有元素时使用的默认值.

  • `price`需要'双倍?'才能让这条线变得有意义. (2认同)