pdf to image
pdf to image

Reputation: 369

Add a parent tag using XML linq

Hello what I want is add another parent tag after the items tag

Here is the example XML:

<parent>
  <items>
    <book>
      <pen></pen>
     </book>
  </items>
</parent>

and here is the desired output:

<parent>
  <items>
   <paper>
    <book>
      <pen></pen>
    </book>
   </paper>
  </items>
</parent>

and here is my code. What's wrong with this?

string xml = "<parent><items>" +
                "<book>" +
                "<pen>" +
                "</pen>" +
                "</book>" +
                "</items></parent>";



XDocument doc = XDocument.Parse(xml);
Console.WriteLine(doc.ToString());
var books = doc.Descendants("items").Elements().First();
doc.Element("items").Add(new XElement("paper", books));
books.Remove();

Console.WriteLine(doc.ToString());

It only gives me error:

Object reference not set to an instance of an object.

pointing to doc.Element("items").Add(new XElement("paper", books));

the answer below which i marked as checked worked in the example xml

but when i used using the long xml it doesn't work anymore

here is the link of the long xml

http://pastebin.com/nb6Pk8bX

and here is the output

http://pastebin.com/WkZEgUYy

and here is the code im using

 XDocument doc = XDocument.Parse(reader);
                var books = doc.Descendants("Layout").Elements().First();
                books.Ancestors().First().Add(new XElement("Page", books));
                books.Remove();

the page tag became the parent. not the layout tag

document>
  <Page>
    <Layout>

Upvotes: 1

Views: 1576

Answers (2)

M. Wiśnicki
M. Wiśnicki

Reputation: 6203

You can do like this, first remove books next add XElement and add again books it's give your destination xml

string xml = "<parent><items>" +
             "<book>" +
             "<pen>" +
             "</pen>" +
             "</book>" +
              "</items></parent>";



 XDocument doc = XDocument.Parse(xml);
 Console.WriteLine(doc.ToString());
 var books = doc.Descendants("items").Elements().First();
 doc.Element("parent").Element("items").Element("book").Remove();
 doc.Element("parent").Element("items").Add(new XElement("paper",books));


Console.WriteLine(doc.ToString());

Edit if you dont know first tag name you can use Root

Gets the root element of the XML Tree for this document.

      doc.Root.Element("items").Element("book").Remove();
      doc.Root.Element("items").Add(new XElement("paper",books));

Edit2 "if the tag after the "items" tag is not a parent tag?"

        doc.Descendants("items").Elements("book").Remove();
        doc.Descendants("items").First().Add(new XElement("paper", books));

Upvotes: 2

Klaudiusz bryjamus
Klaudiusz bryjamus

Reputation: 326

This should work:

XDocument doc = XDocument.Parse(xml);
var books = doc.Descendants("items").Elements().First();
books.Ancestors().First().Add(new XElement("paper", books));
books.Remove();

Upvotes: 1

Related Questions