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