繁体   English   中英

如何在xml中使用linq to xml在xml中不存在xml节点?

[英]How can I catch if an xml node does not exist in xml using linq to xml in c#?

我的问题是,在我的xml数据中,有时某个特定节点不存在,我怎样才能捕获它以避免"Object reference not set to an instance of an object." error "Object reference not set to an instance of an object." error ,只是跳过该值并继续在列表视图中添加项目?

这是我的linq到xml的查询

var summary = from r in doc.Descendants("TrxDetailCard") 
                      select new 
                      {
                          Account_Type = r.Element("Account_Type_CH").Value,
                          Captured = r.Element("Captured").Value,
                          Trans_Type_ID = r.Element("Trans_Type_ID").Value,
                          Acct_Num_CH = r.Element("Acct_Num_CH").Value,
                          Tip_Amt_MN = r.Element("Tip_Amt_MN").Value,
                          Total_Amt_MN = r.Element("Total_Amt_MN").Value,
                          Date_DT = r.Element("Date_DT").Value,
                      };

Tip_Amt_MN有时不存在

在listview中添加项目

foreach (var i in summary)
        {
            ListViewItem it = new ListViewItem(i.Account_Type.ToString());
            it.SubItems.Add(i.Captured.ToString());
            it.SubItems.Add(i.Trans_Type_ID.ToString());
            it.SubItems.Add(i.Acct_Num_CH.ToString());
            it.SubItems.Add(i.Tip_Amt_MN.ToString());
            it.SubItems.Add(i.Total_Amt_MN.ToString());
            it.SubItems.Add(i.Date_DT.ToString());
            listView1.Items.Add(it);
        }

如果您不介意将属性设置为null,则可以将XElement强制转换为字符串。 换句话说,如果Account_Type_CH元素不存在,则不会抛出异常:

Account_Type = (string)r.Element("Account_Type_CH")

在我不想破解查询的情况下,我倾向于自由使用FirstOrDefault():

r.Element("Tip_Amt_MN").Value

变为:

r.Elements("Tip_Amt_MN").Select(x => x.Value).FirstOrDefault()

暂无
暂无

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

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