Create blank XML File and then Append to it

10,888

You'll need a root element in the file:

xmlFile.Add( new XElement( "Contacts" ) );

Although the error you are getting suggests something else is going on. Perhaps Filename is null?

Share:
10,888
RXC
Author by

RXC

Updated on June 04, 2022

Comments

  • RXC
    RXC over 1 year

    I am writing a windows forms program in C# and I want to be able to save information to an XML file. When I first create the XML file, I just want to be able to ad the declaration

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    

    and then the root node which I want called "Contacts".

    The final file should look like:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <Contacts>
        <Contact>
            <Name>name</Name>
            <Address>address</Address>
        <Contact>
    <Contacts>
    

    There will be multiple <Contact></Contact> elements.

    The problem I am having is when I first create the XML file.

    My XML operations are in their own class. This is the method to create the file:

    public void createFile()
        {
            if (!File.Exists(fileName))
            {
                //Populate with data here if necessary, then save to make sure it exists
                xmlFile = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XComment("XML File for storing " + RootName));
                xmlFile.Save(FileName);
            }
        }
    

    When I try to run this, I get an ArgumentNullException was unhandled error.

    Any ideas how to actually get the data in the file and have it save? Thanks

    • Tony Hopkinson
      Tony Hopkinson about 10 years
      have you considered debugging? Or looking at the stacktrace to see which argument of what is null.
  • RXC
    RXC about 10 years
    I added that in there right after the new XDocument statement, and I still get the error. The file never gets created. It seems like I have to populate the file with something, but I'm not sure what.
  • RXC
    RXC about 10 years
    The xmlFile.Save(FileName) is throwing the error. I found out the problem, I was never setting the FileName, which is a public accessor for a private backing field.
  • Chris
    Chris about 10 years
    Hehe as I guessed then.