Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Remove Root Element in C#/

Tags:

c#

xml

I'm new to XML & C#. I want to remove root element without deleting child element. XML file is strudctured as below.

   <?xml version="1.0" encoding="UTF-8"?>
   <dataroot generated="2013-07-06T20:26:48" xmlns:od="urn:schemas-microsoft-com:officedata">
     <MetaDataSection> 
       <Name>KR04</Name> 
       <XMLCreationDate>02.05.2013 9:52:41 </XMLCreationDate> 
       <Address>AUTOMATIC</Address> 
       <Age>22</Age> 
     </MetaDataSection> 
   </dataroot>

I want to root element "dataroot", so it should look like below.

    <?xml version="1.0" encoding="UTF-8"?>
     <MetaDataSection> 
       <Name>KR04</Name> 
       <XMLCreationDate>02.05.2013 9:52:41 </XMLCreationDate> 
       <Address>AUTOMATIC</Address> 
       <Age>22</Age> 
     </MetaDataSection> 

Deleting child elements look like easy, but I don't know how to delete root element only. Below is the code I've tried so far.

        XmlDocument xmlFile = new XmlDocument();
        xmlFile.Load("path to xml");

        XmlNodeList nodes = xmlFile.SelectNodes("//dataroot");

        foreach (XmlElement element in nodes)
        {
            element.RemoveAll();
        }

Is there a way to remove root element only? without deleting child elements? Thank you in advnace.

like image 831
Toykeat Avatar asked Jul 06 '13 13:07

Toykeat


1 Answers

Rather than trying to actually remove the root element from an existing object, it looks like the underlying aim is to save (or at least access) the first child element of the root element.

The simplest way to do this is with LINQ to XML - something like this:

XDocument input = XDocument.Load("input.xml");
XElement firstChild = input.Root.Elements().First();
XDocument output = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                                 firstChild);
output.Save("output.xml");

Or if you don't need the XML declaration:

XDocument input = XDocument.Load("input.xml");
XElement firstChild = input.Root.Elements().First();
firstChild.Save("output.xml");
like image 124
Jon Skeet Avatar answered Nov 14 '22 21:11

Jon Skeet