Linq To Xml Null检查属性

How*_*wel 10 c# linq linq-to-xml

<books>
   <book name="Christmas Cheer" price="10" />
   <book name="Holiday Season" price="12" />
   <book name="Eggnog Fun" price="5" special="Half Off" />
</books>
Run Code Online (Sandbox Code Playgroud)

我想用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
                                   };
Run Code Online (Sandbox Code Playgroud)

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

谢谢,

  • 贾里德

Ahm*_*eed 11

您可以将属性强制转换为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")
            };
Run Code Online (Sandbox Code Playgroud)