如何在C#/中删除根元素 [英] How to Remove Root Element in C#/

查看:67
本文介绍了如何在C#/中删除根元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是XML&的新手.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>

我想将元素"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.

推荐答案

最简单的方法是使用LINQ to XML-之类的东西:

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

或者如果您不需要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");

这篇关于如何在C#/中删除根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆