0

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);
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
wee hee
  • 85
  • 9
  • 1
    Does this answer your question? [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) – derpirscher Mar 07 '22 at 06:30

1 Answers1

0

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);
}
Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21
  • Thank you for showing your syntax! Such a cleaner code too. – wee hee Mar 08 '22 at 00:35
  • Use Any() instead of Count() if don't need that number: using Count() will enumerate ALL elements to build up the final number; using Any() the enumeration will stop at the first element. – Rubidium 37 Aug 09 '23 at 10:51