0

I cannot figure out how to set a default value to an XmlNode.

I have an XmlNode called RequirementMinTime and I want to set it to the value of "0" when that node is not in the xml document. Here is the code I'm trying which is not working.

        XmlReader reader = XmlReader.Create(xmlpath, settings);
        XmlDocument doc = new XmlDocument();

        doc.Load(reader);

       if (GlobalNode.SelectSingleNode("MinTimeMs") == null)
        {
            RequirementMinTime.Attributes["MinTimeMs"].Value = "0";
        }
        else
        {
            RequirementMinTime = GlobalNode.SelectSingleNode("MinTimeMs");
        }

I am getting the following error in the if statement

"System.NullReferenceException: 'Object reference not set to an instance of an object.'"

this is the object declaration:

    public static XmlNode RequirementMinTime
    {
        get;
        set;
    }
Shayki Abramczyk
  • 36,824
  • 16
  • 89
  • 114
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Dave Sep 17 '18 at 13:01

2 Answers2

1

here is the solution

    XmlReader reader = XmlReader.Create(xmlpath, settings);
    XmlDocument doc = new XmlDocument();

    doc.Load(reader);

   if (GlobalNode.SelectSingleNode("MinTimeMs") == null)
    {
        XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "MinTimeMs", "");
        newNode.InnerText = "0";
        GlobalNode.AppendChild(newNode);    
        RequirementMinTime = GlobalNode.SelectSingleNode("MinTimeMs");
    }
    else
    {
        RequirementMinTime = GlobalNode.SelectSingleNode("MinTimeMs");
    }
0

You need to create the node, otherwise you can not set a value (assuming your XmlDocument is named xmlDoc:

if (GlobalNode.SelectSingleNode("MinTimeMs") == null)
{
    RequirementMinTime = xmlDoc.CreateElement("MinTimeMs");
    RequiredMinTime.Value = "0";
}
else
{
    RequirementMinTime = GlobalNode.SelectSingleNode("MinTimeMs");
}
Sefe
  • 13,731
  • 5
  • 42
  • 55