Here is my XML file
<?xml version="1.0" encoding="UTF-8"?>
<Data>
<Month>
<Month_Number>1</Month_Number>
<Tool>
<Name>Help</Name>
<Count>40</Count>
</Tool>
</Month>
<Month>
<Month_Number>2</Month_Number>
<Tool>
<Name>Help</Name>
<Count>50</Count>
</Tool>
</Month>
</Data>
I would like to see if there is a Month which has Month_Number with the value of 3. If it doesn't exist not I would like to add a Month which has a Month_Number with the value of 3. The above XML file will turn into the following:
<Data>
<Month>
<Month_Number>1</Month_Number>
<Tool>
<Name>Help</Name>
<Count>40</Count>
</Tool>
</Month>
<Month>
<Month_Number>2</Month_Number>
<Tool>
<Name>Help</Name>
<Count>50</Count>
</Tool>
</Month>
<Month>
<Month_Number>3</Month_Number>
<Tool>
<Name>Help</Name>
<Count>50</Count>
</Tool>
</Month>
</Data>
And here is the I came up with. Code partially works by going through each month and telling me if it exists. however, it errors when creating a new node
An unhandled exception of type 'System.NullReferenceException' occurred
because of node.AppendChild(xMonth);
code:
XmlDocument tallyFile = new XmlDocument();
tallyFile.Load(tallyFilePath);
XmlNode node = tallyFile["Data"]; //mainSettingsDoc["Data"]["Month"]
foreach (XmlNode childNode in node.ChildNodes)
{
// IF MONTH EXISTS
if (childNode["Month_Number"].InnerText.Equals("3"))
{
MessageBox.Show("MONTH EXISTS!");
} // END IF MONTH EXISTS
else // IF MONTH DOESNT EXISTS
{
XmlElement xMonth = tallyFile.CreateElement(string.Empty, "Month", string.Empty);
node.AppendChild(xMonth);
MessageBox.Show("MONTH DOESNT EXIST!");
} // END IF MONTH DOESNT EXIST
} // END OF FOREACH LOOP
tallyFile.Save(tallyFilePath);