Search code examples
c#xelementxattribute

Reading from an attribute that might be missing in a xelement.add method in C#


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));

Solution

  • 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.