Linq to xml not able to add new elements
- by Fore
We save our xml in a "text" field in the database. So first I check if it exist any xml, if not I create a new xdocument, fill it with the necessary xml. else i just add the new element. Code looks like this:
XDocument doc = null;
if (item.xmlString == null || item.xmlString == "")
{
doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("DataTalk", new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute(XNamespace.Xmlns + "xsd", "http://www.w3.org/2001/XMLSchema"), new XElement("Posts", new XElement("TalkPost"))));
}
else
{
doc = XDocument.Parse(item.xmlString);
}
This is working alright to create a structure, but then the problem appears, when I want to add new TalkPost. I get an error saying incorrectly structured document.
The following code when adding new elements:
doc.Add(new XElement("TalkPost", new XElement("PostType", newDialog.PostType),
new XElement("User", newDialog.User), new XElement("Customer", newDialog.Customer),
new XElement("PostedDate", newDialog.PostDate), new XElement("Message", newDialog.Message)));