Linq to xml not able to add new elements

Posted by Fore on Stack Overflow See other posts from Stack Overflow or by Fore
Published on 2011-01-07T10:39:47Z Indexed on 2011/01/07 10:53 UTC
Read the original article Hit count: 346

Filed under:
|

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)));

© Stack Overflow or respective owner

Related posts about Xml

Related posts about linq-to-xml