GrayFullBuster
GrayFullBuster

Reputation: 1063

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

My problem is that in data of my xml sometimes a specific node does not exists how can I catch that to avoid "Object reference not set to an instance of an object." error and just skip that value and continue adding items in listview?

Here is the query of my linq to 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,
                      };

The Tip_Amt_MN sometimes does not exists

Add items in 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);
        }

Upvotes: 0

Views: 804

Answers (2)

Cory Nelson
Cory Nelson

Reputation: 29991

I tend to make liberal use of FirstOrDefault() in situations where I don't want to break a query up:

r.Element("Tip_Amt_MN").Value

becomes:

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

Upvotes: 1

McGarnagle
McGarnagle

Reputation: 102763

If you don't mind the property being set to null, then you can cast the XElement to string. In other words, this won't throw an exception if the Account_Type_CH element doesn't exist:

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

Upvotes: 1

Related Questions