Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...