Question

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

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top