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));
有帮助吗?

解决方案

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.

其他提示

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)); 
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top