Linq to xml无法添加新元素

问题描述:

我们将xml保存在数据库的“文本”字段中。所以首先我检查它是否存在任何xml,如果没有,我创建一个新的xdocument,用必要的xml填充它。否则我只是添加新的元素。代码如下所示:Linq to xml无法添加新元素

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

这是工作好吗创建一个结构,但随后出现的问题,当我要添加新的TalkPost。我收到一个错误,说结构错误的文档。 添加新的元素时,下面的代码:

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

相反的doc.Add(...,尝试doc.Root.Add(...

加入一个新元素DOC意味着你基本上是试图添加另一根元素,因此无效的XML异常。

在回应评论:

我想你应该尝试再doc.Root.Element("Posts").Add(...作为将一个元素添加到Posts元素,而不是根源。

+0

您好,感谢您的帮助,现在它的工作,我现在得到的唯一的问题是,它就会在同一个“级别”的“帖子” saven,但它应该像被保存在下面文章:,然后所有非常感谢 – Fore 2011-01-07 11:06:52