user1732337
user1732337

Reputation: 23

Linq XML add new parent

With linq XML is it possible to add a new father to existing nodes? Take this XML excerpt:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<items>
 <book>
  <title>Title 1</title>
  <author>Author 1</author>
 </book>
 <book>
  <title>Title 2</title>
  <author>Author 2</author>
 </book>
 <car>
  <model>Tesla</model>
 </car>
</items>

Is it possible to add a new father "books" to book like this:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<items>
 <books>
  <book>
   <title>Title 1</title>
   <author>Author 1</author>
  </book>
  <book>
   <title>Title 2</title>
   <author>Author 2</author>
  </book>
 </books>
  <car>
   <model>Tesla</model>
  </car>
</items>

This is not working because it is cloning the nodes:

doc.Element("items").Add(new XElement("books",doc.Element("items").Elements("book")));

Upvotes: 0

Views: 210

Answers (1)

Andrey Korneyev
Andrey Korneyev

Reputation: 26856

You can remove your existed <book> elements from <items> node after adding them under new <books> parent node:

var books = doc.Element("items").Elements("book");
doc.Element("items").Add(new XElement("books", books));
books.Remove();

Upvotes: 1

Related Questions