如何将XElement添加到文档中,以避免出现“结构不正确的文档"错误? [英] How do I add an XElement to a document, avoiding the "incorrectly structured document" error?
问题描述
// Remove element with ID of 1
var userIds = from user in document.Descendants("Id")
where user.Value == "1"
select user;
userIds.Remove();
SaveAndDisplay(document);
// Add element back
var newElement = new XElement("Id", "0",
new XElement("Balance", "3000"));
document.Add(newElement);
SaveAndDisplay(document);
添加元素back块是问题所在.谈到添加时,状态如下:
The add element back block is the problem. As when it gets to the add it states:
此操作将创建一个 结构不正确的文档.
This operation would create an incorrectly structured document.
我犯了什么愚蠢的错误?
What stupid mistake am I making?
是的,我正在读为XDocument
,而不是XElement
.关于何时偏爱另一方的任何建议?
Yes, I was reading as an XDocument
, not XElement
. Any advice on when to favour one or the other?
推荐答案
您似乎正在尝试添加一个新元素作为文档根目录的子元素.如果是这样,则需要将Add
语句更改为以下内容.
It looks like you are trying to add a new element as a child of your document's root. If so, then you need to change your Add
statement to the following.
var newElement = new XElement("Id", "0", new XElement("Balanace", "3000"));
document.Root.Add(newElement);
直接添加到文档中会添加另一个根元素,这违反了XML结构.
Adding directly to the document adds another root element, which violates the XML structure.
这篇关于如何将XElement添加到文档中,以避免出现“结构不正确的文档"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!