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;



        // Add element back
        var newElement = new XElement("Id", "0", 
            new XElement("Balance", "3000"));


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?


Yes, I was reading as an XDocument, not XElement. Any advice on when to favour one or the other?


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"));

Adding directly to the document adds another root element, which violates the XML structure.

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) or document.FirstNode.Add(newElement)

Need Your Help

Node NPM proxy authentication - how do I configure it?

node.js proxy npm http-proxy

I'm new to Node and trying to install TypeScript using the following command:

Python integer division yields float

python integer python-3.x division

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32