PDA

View Full Version : XML Saving error



alexgeek
January 11th, 2008, 08:44 AM
I get the following error when i try to add a new <person> to my XML document.

System.InvalidOperationException: This document already has a 'DocumentElement' node.

The XML file looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<usersettings>
<person>
<name>Alex</name>
<age>14</age>
<lang>PHP</lang>
</person>
<person>
<name>Swagner</name>
<age>14</age>
<lang>HTML/CSS</lang>
</person>
</usersettings>

I tried to add a new <person> element. I can correctly read the file at the moment, but I can't append a new <person> to the object (I can to a brand new XML document but that's not what I want).

Here's my code:


class Program
{
private const string FILE = @"xml/usersettings.xml";
static void Main(string[] args)
{
try
{
XmlDocument xml = new XmlDocument();
xml.Load(FILE);
XmlNodeList people = xml.GetElementsByTagName("person");
foreach (XmlNode node in people)
{
XmlElement person = (XmlElement)node;

string name = person.GetElementsByTagName("name")[0].InnerText;
int age = Convert.ToInt32(person.GetElementsByTagName("age")[0].InnerText);
string lang = person.GetElementsByTagName("lang")[0].InnerText;

Console.WriteLine("Name: {0}", name.ToString());
Console.WriteLine("Age: {0}", age.ToString());
Console.WriteLine("language: {0}\n", lang.ToString());
}
XmlElement newp = xml.CreateElement("person");
xml.AppendChild(newp);
xml.Save(FILE);
}
catch (Exception e)
{
Console.WriteLine("Error: \n\n {0}", e.ToString());
System.IO.StreamWriter err = new System.IO.StreamWriter(@"err.txt");
err.WriteLine("Error Message:\n\n{0}", e.ToString());
err.Close();
}
finally
{
string s = Console.ReadLine();

}
}
}

kirupa
January 11th, 2008, 09:43 PM
Try creating your new element in the parent of the node referenced by xml. Also, try using the debugger in VS by setting breakpoints and going line-by-line. That makes solving these things much easier :)

alexgeek
January 13th, 2008, 02:00 PM
Okay I will try when I get time.
Thanks!

alexgeek
January 13th, 2008, 02:06 PM
I would assume I'd do this:


XmlElement newp = xml.ParentNode.CreateElement("person");


But that doesn't work. ParentNode does not contain the CreateElement method.

kirupa
January 13th, 2008, 08:48 PM
No, by parent node, I mean add your person to the usersettings node. Your xml value only stores person nodes...not their parent, which would be usersettings.

alexgeek
January 14th, 2008, 06:11 PM
I think I understand, will try it tomorrow.
Thank you!