How to Remove Root Element in C#/

前端 未结 2 1840
北海茫月
北海茫月 2020-12-19 11:23

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

   

        
相关标签:
2条回答
  • 2020-12-19 12:06

    if you need to do in c# coding means

    Solution

     foreach (XElement item in Element.Descendants("dataroot").ToList())
            {
                item.ReplaceWith(item.Nodes());
            }
    
    0 讨论(0)
  • 2020-12-19 12:19

    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");
    
    0 讨论(0)
提交回复
热议问题