21
        // 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?

Steve Guidi
  • 19,700
  • 9
  • 74
  • 90
Finglas
  • 15,518
  • 10
  • 56
  • 89
  • On a side note, your `newElement` object stores the `Balance` node as a child of `Id`. This doesn't match your expected XML structure. – Steve Guidi Jan 21 '10 at 17:43
  • You're right, but you can ignore the xml structure, I thought it was required but I can literally add anything. – Finglas Jan 21 '10 at 17:45

2 Answers2

40

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.

Steve Guidi
  • 19,700
  • 9
  • 74
  • 90
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.Root.Add(newElement) or document.FirstNode.Add(newElement)

Patrick Karcher
  • 22,995
  • 5
  • 52
  • 66
  • Even more correctly: `if (document.Root.FirstNode != null) document.Root.FirstNode.AddAfterSelf(newElement); else document.Root.AddFirst(newElement);` – Csaba Toth Apr 10 '13 at 20:59