小编Toy*_*eat的帖子

如何在C#中删除根元素

我是XML&C#的新手.我想删除根元素而不删除子元素.XML文件的结构如下.

   <?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>
Run Code Online (Sandbox Code Playgroud)

我想根元素"dataroot",所以它应该如下所示.

    <?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> 
Run Code Online (Sandbox Code Playgroud)

删除子元素看起来很简单,但我不知道如何只删除根元素.下面是我到目前为止尝试过的代码.

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

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

        foreach (XmlElement element in nodes)
        {
            element.RemoveAll();
        }
Run Code Online (Sandbox Code Playgroud)

有没有办法只删除根元素?不删除子元素?谢谢你的帮助.

c# xml

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×1

xml ×1