Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add an XElement to a document, avoiding the "incorrectly structured document" error?

Tags:

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

like image 391
Finglas Avatar asked Jan 21 '10 17:01

Finglas


1 Answers

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.

like image 195
Steve Guidi Avatar answered Sep 30 '22 02:09

Steve Guidi