Search code examples
c#xmlsiblings

How do i Check if a xml Sibling has attributes?


My program is doing weird stuff if i delete one of my Attributes because it is not able to handle Siblings without Attributes. Now i googled for a while but i am not able to find a good way to check for attributes.

Whats the way you prefer checking for attributes?

while (FXMLNode != null)
{
     if (FXMLNode.Name.ToLower() == "datei")
     {
           xmlInformationen oInfo = new xmlInformationen();
           oInfo.Dateipfad = FXMLNode.InnerText;

           if (FXMLNode.Attributes["checked"].Value.ToString() == "true")
                oInfo.CheckBox = true;
           else if (FXMLNode.Attributes["checked"].Value.ToString() == "false")
                oInfo.CheckBox = false;
           else if(FXMLNode == null)
                oInfo.CheckBox = true;
           else
                oInfo.CheckBox = true;

           lstAttribute.Add(oInfo);
           iCounter++;

           if (FXMLNode.NextSibling == null)
           {
                FXMLNode = FXMLNode.FirstChild;
           }
           else
           {
                FXMLNode = FXMLNode.NextSibling;
           }
      }
      else
      {
           if (FXMLNode.NextSibling == null)
           {
                FXMLNode = FXMLNode.FirstChild;
           }
           else
           {
                FXMLNode = FXMLNode.NextSibling;
           }
      }
}

Solution

  • You are accessing the value of an attribute without knowing if the attribute exists or not. Rewrite your code to check for the attribute first:

    oInfo.CheckBox = true;
    if(FXMLNode == null) oInfo.CheckBox = true; //not sure why you set it to true here
    else if (FXMLNode.HasAttribute("checked"))
    {
         if (FXMLNode.Attributes["checked"].Value.ToString() == "true")
                oInfo.CheckBox = true;
         else if (FXMLNode.Attributes["checked"].Value.ToString() == "false")
                oInfo.CheckBox = false;
    }
    

    Please note that checking if the Xml element is null should be the first thing you do. If it's null then it surely won't have any attributes but you'll have an exception.