【问题标题】:Linq to xml not able to add new elementsLinq to xml 无法添加新元素
【发布时间】:2011-01-07 20:24:17
【问题描述】:

我们将 xml 保存在数据库的“文本”字段中。所以首先我检查它是否存在任何xml,如果不存在我创建一个新的xdocument,用必要的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)));

【问题讨论】:

    标签: xml linq-to-xml


    【解决方案1】:

    试试doc.Root.Add(...,而不是doc.Add(...

    向 doc 添加另一个元素意味着您实际上是在尝试添加另一个根元素,因此是无效的 XML 异常。

    回应评论:

    我认为您应该尝试doc.Root.Element("Posts").Add(...,因为这会将一个元素添加到Posts 元素,而不是根。

    【讨论】:

    • 嗨,感谢您的帮助,现在它正在工作,我现在唯一遇到的问题是它被保存在与“帖子”相同的“级别”中,但它应该保存在下面的帖子中,例如: 然后是所有 非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    相关资源
    最近更新 更多