【发布时间】: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