开发者

Linq to xml not able to add new elements

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 XDe开发者_JAVA技巧claration("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)));


Instead of doc.Add(..., try doc.Root.Add(...

Adding another element to doc means that you are essentially trying to add another root element, hence the invalid XML exception.

In response to the comment:

I think you should try then doc.Root.Element("Posts").Add(... As that will add an element to the Posts element, rather than the root.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜