Qwer
Qwer

Reputation: 3

Avoid NullReferenceException while parsing through a XML-File with missing elements

I have a problem with a NullReferenceException while reading data from a XML file. Sometimes some nodes don't exist, see 'Profil' - I tried using the ?? operator, but this would only work if the node would exist. Then I tried to check if the node exists with

if([["Kante"]["Profil"]["Profilbreite"] != null) 

but if for example ["Profil"] doesn't exist, it throws the exception.

I would love not to use try{}catch() for every value I need.

XmlDocument XMLDoc = new XmlDocument();
XMLDoc.Load(file);

XmlNodeList NL_Stammdaten = XMLDoc.SelectNodes("//*[local-name()='AbwassertechnischeAnlage']");

for (int i = NL_Stammdaten.Count - 1; i >= 0; i--)
{
    string Objektbezeichnung = "";
    int Profilbreite = 0;

    Objektbezeichnung = NL_Stammdaten[i]["Objektbezeichnung"].InnerText ?? ""; //First attempt with the ?? Operator
    if (NL_Stammdaten[i]["Objektbezeichnung"] != null) Objektbezeichnung = NL_Stammdaten[i]["Objektbezeichnung"].InnerText ?? ""; //Second attempt with ?? Operator and if(null)
    if (NL_Stammdaten[i]["Kante"]["Profil"]["Profilbreite"] != null) Profilbreite = Convert.ToInt32(NL_Stammdaten[i]["Kante"]["Profil"]["Profilbreite"].InnerText ?? ""); //Throws exception if the ["Profil"] -Node dosn't exists in the XML
}

The XML-File:

<Data>
    <AbwassertechnischeAnlage>
        <Objektbezeichnung>113062SE04</Objektbezeichnung>
        <Kante>
            <KantenTyp>1</KantenTyp>
            <Profil>
                <Profil>1</Profil>
                <Profilbreite>300</Profilbreite>
            </Profil>
        </Kante>
    </AbwassertechnischeAnlage>
    <AbwassertechnischeAnlage>
        <Objektbezeichnung>113062SE04</Objektbezeichnung>
        <Kante>
            <KantenTyp>1</KantenTyp>
            <!--<Profil></Profil> dosn't exists -->
        </Kante>
    </AbwassertechnischeAnlage>
</Data>

Upvotes: 0

Views: 64

Answers (1)

Fruchtzwerg
Fruchtzwerg

Reputation: 11389

Using the Null-conditional operator like

if (NL_Stammdaten[i]?["Kante"]?["Profil"]?["Profilbreite"] != null)

should do the trick.

Used to test for null before performing a member access (?.) or index (?[) operation. These operators help you write less code to handle null checks, especially for descending into data structures.

This means you can simply chain the array accessors without writing extensive null checks.

Upvotes: 1

Related Questions