XML到LINQ与检查null元素 [英] XML to LINQ with Checking Null Elements

查看:152
本文介绍了XML到LINQ与检查null元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面对的解析XML文档转换成使用LINQ对象的情况。在解析我检查,以确保元素不是空着手分析出它们的值了。反正是有简化这个声明?

The situation I am faced with is parsing an XML document into an object using Linq. During the parse I am checking to make sure Elements are not null before proceeding to parse out their values. Is there anyway to simplify this statement?

  var variable = (from x in xdoc.Descendants("Root")
                 select new AccountingResponse
                 {      
                 NetCharge = x.Element("Charges") != null && x.Element("Charges").Element("NetCharge") != null ? x.Element("Charges").Element("NetCharge").Value : "0",
                 TotalCharge = x.Element("Charges") != null && x.Element("Charges").Element("TotalCharge") != null ? x.Element("Charges").Element("TotalCharge").Value : "0"
                 }).SingleOrDefault();



总之,我不想继续检查,如果每一行存在的节点。我知道我可以测试,看看之前的解析节点存在,但也有可能需要解析创建AccountingResponse其他数据,我想避免的if语句,只有在一个时间解析XML的一部分了。

To summarize, I do not want to continue to check if the nodes exist on each line. I know I can test to see if the node exists prior to the parsing, but there may be other data that needs parsed to create the AccountingResponse and I want to avoid if statements that only parse a portion of the XML out at a time.

也许我这样做是完全错误的,有一个更好的办法!

Or perhaps I'm doing this completely wrong and there's a better way!

推荐答案

一个简单的选择是使用元素,而不是元素 - 这将返回一个零长度序列如果元素是不存在。所以,你可以使用:

One simple option is to use Elements rather than Element - that will return a zero-length sequence if the element isn't present. So you can use:

from x in xdoc.Descendants("Root")
select new AccountingResponse
{      
    NetCharge = x.Elements("Charges")
                 .Elements("NetCharge")
                 .Select(y => (int) y)
                 .FirstOrDefault(),
    TotalCharge = x.Elements("Charges")
                   .Elements("TotalCharge")
                   .Select(y => (int) y)
                   .FirstOrDefault(),
}).SingleOrDefault();



(请注意,您原来的代码将不能编译,因为是一个字符串,而0是一个int ...)

(Note that your original code wouldn't compile, as Value is a string whereas 0 is an int...)

这篇关于XML到LINQ与检查null元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆