Linq to xml 无法添加新元素
我们将 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)));
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)));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用
doc.Root.Add(...
) 代替 doc.Add(...) 将另一个元素添加到 doc 意味着您本质上是在尝试添加另一个根元素,因此出现无效的 XML 异常。
响应评论:
我认为您应该尝试
doc.Root.Element("Posts").Add(...
因为这会将元素添加到Posts
元素,而不是根元素。Instead of
doc.Add(...
, trydoc.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 thePosts
element, rather than the root.