// 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);
The add element back block is the problem. As when it gets to the add it states:
添加元素后块是问题所在。当它到达add时,它说:
This operation would create an incorrectly structured document.
这个操作将创建一个不正确的结构文档。
What stupid mistake am I making?
我犯了什么愚蠢的错误?
Edit:
编辑:
Yes, I was reading as an XDocument
, not XElement
. Any advice on when to favour one or the other?
是的,我读的是XDocument,不是XElement。对于什么时候该支持哪一方,有什么建议吗?
2 个解决方案
#1
38
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);
Adding directly to the document adds another root element, which violates the XML structure.
直接向文档添加另一个根元素,这违反了XML结构。
#2
8
You're effectively trying to add a new root element, which these objects don't like. I assume document
is an XDocument? Place it further inside the root node, by adding it to the root node. Use:
您实际上正在尝试添加一个新的根元素,这些对象不喜欢。我认为document是XDocument?通过将其添加到根节点中,将其进一步放置到根节点中。使用:
document.Root.Add(newElement)
or document.FirstNode.Add(newElement)
document.Root.Add(newElement)或document.FirstNode.Add(newElement)
#1
38
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);
Adding directly to the document adds another root element, which violates the XML structure.
直接向文档添加另一个根元素,这违反了XML结构。
#2
8
You're effectively trying to add a new root element, which these objects don't like. I assume document
is an XDocument? Place it further inside the root node, by adding it to the root node. Use:
您实际上正在尝试添加一个新的根元素,这些对象不喜欢。我认为document是XDocument?通过将其添加到根节点中,将其进一步放置到根节点中。使用:
document.Root.Add(newElement)
or document.FirstNode.Add(newElement)
document.Root.Add(newElement)或document.FirstNode.Add(newElement)