如何将 XElement 添加到文档中,避免出现“结构错误的文档”错误?
// 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);
添加元素后块是问题所在。当它到达添加时,它指出:
此操作将创建一个 文档结构不正确。
我犯了什么愚蠢的错误?
编辑:
是的,我是作为XDocument
而不是XElement
来阅读的。关于何时支持其中之一有什么建议吗?
// 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:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您似乎正在尝试添加一个新元素作为文档根目录的子元素。如果是这样,那么您需要将
Add
语句更改为以下内容。直接添加到文档中会添加另一个根元素,这违反了 XML 结构。
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.Adding directly to the document adds another root element, which violates the XML structure.
您实际上正在尝试添加这些对象不喜欢的新根元素。我假设
document
是 XDocument?通过将其添加到根节点,将其进一步放置在根节点内。使用:document.Root.Add(newElement)
或document.FirstNode.Add(newElement)
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.Root.Add(newElement)
ordocument.FirstNode.Add(newElement)