Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

xml - How to Remove Root Element in C#/

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...