0

I am trying to create a XElement that reads from another XElement built from a file. Below is a sample of the code. My question is how do I code around a source attribute that might not be there? docHeader and invoice are XElements. When running this where one attribute is missing, I get a "Object reference not set to an instance of an object" error.

I guess I am asking is there a 'safe' way to read elements and attributes in case they are not there?

invoice.Add(
    new XAttribute("InvoiceNumber", docHeader.Attribute("InvoiceNumber").Value), 
    new XAttribute("InvoiceSource", docHeader.Attribute("InvoiceSource").Value));
L.B
  • 114,136
  • 19
  • 178
  • 224
Styxtb1598
  • 23
  • 2

2 Answers2

0

You are getting the exception because if the attribute InvoiceSource is not present, docHeader.Attribute("InvoiceSource") returns null. Simple check like

if (docHeader.Attribute("InvoiceSource") != null)
{
    // here you can be sure that the attribute is present
}

will be sufficient.

Nikola Anusev
  • 6,940
  • 1
  • 30
  • 46
  • Thanks Nikola. I was trying to not have to break the assignments down since I have about 40 of them to do, but I guess I don't have a choice. – Styxtb1598 Mar 24 '12 at 17:45
0

Try breaking up the code so that it's more flexible and readable.

var src = docHeader.Attribute("InvoiceSource");
var num = docHeader.Attribute("InvoiceNumber");

if(src != null && num != null)
{
  invoice.Add(
    new XAttribute("InvoiceNumber", num.value), 
    new XAttribute("InvoiceSource", src.value)); 
}
Chris Gessler
  • 22,727
  • 7
  • 57
  • 83