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);
CodePudding user response:
It is easier to implement by using LINQ to XML API. It is available in the .Net Framework since 2007.
c#
void Main()
{
const string inputFile = @"e:\Temp\weehee.xml";
const string outputFile = @"e:\Temp\weehee_2.xml";
XDocument xdoc = XDocument.Load(inputFile);
if (xdoc.Descendants("Month")
.Where(x => x.Element("Month_Number").Value.Equals("3")).Count() == 0)
{
xdoc.Root.Add(new XElement("Month",
new XElement("Month_Number", "3"),
new XElement("Tool",
new XElement("Name", "Help"),
new XElement("Count", "50")
)));
}
xdoc.Save(outputFile);
}