I have a windows form application I am writing and I want to create an xml file and add data to it.
The code is below.
xmlFile = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("XML File for storing " + RootName));
xmlFile.Add(new XElement(RootName));
// Loop through the list and create a new element for each item in the list
foreach (Contact c in contactsList)
{
try
{
xmlFile.Add(new XElement("Contact",
new XElement("Name", c.Name),
new XElement("Email", c.EmailAddress),
new XElement("Mobile Number", c.MobileNumber),
new XElement("Mobile Carrier", c.sMobileCarrier)
)
);
}
catch
{
MessageBox.Show("ERROR WITH NEW ELEMENTS");
}
}
xmlFile.Save(FileName);
When I run the program, the try block throws and error and I get the message box error. When I debug, the program says the exception has to do with:
The ' ' character, hexadecimal value 0x20, cannot be included in a name.
I am not sure what this means, because I checked all the values being passed in and upto the point of entry, there is something there.
Am I missing a parameter in the xmlFile.Add() statement?
One last question, when I insert the Root element after creating the XDocument object,
in the file it comes out as <Contacts />, which I want to be the closing root tag.
How do I get the starting tag inserted, and then when I go to save at the end, it appends the closing tag?
Thanks
Update--------------------- Thanks to MarcinJuraszek, I was able to get past that exception being thrown, but now i get this error:
This operation would create an incorrectly structured document.
Any ideas what that means or what is causing it?