Share via


ADD Root Node to XML in C#

Question

Saturday, November 1, 2014 10:09 AM

Hi,

     I have a XML file as shown below

     <?xml version="1.0"?>
       <TP>
            <tg1></tg1>

            <tg2></tg2> 

            <tg3></tg3>   

            <tg4></tg4>

     </TP>

I want my results as (adding a root node)

<?xml version="1.0"?>

<MAIN>

       <TP>
            <tg1></tg1>

            <tg2></tg2> 

            <tg3></tg3>   

            <tg4></tg4>

     </TP>

</MAIN>

Can anyone solve this to me.?

Thanks

All replies (6)

Saturday, November 1, 2014 10:36 AM âś…Answered

Here you go:

string xmlFile = @"C:\yourFile.xml";
XElement doc = XElement.Load(xmlFile);
XElement root = new XElement("MAIN", doc);

root.Save(xmlFile);

Please remember to mark helpful posts as answer and/or helpful.


Saturday, November 1, 2014 10:43 AM

Thanks a lot. Thank you.. :) :)

and magnus can we add a dataset name to nested tables in xml file?


Saturday, November 1, 2014 10:50 AM

How about:

            var xml = XDocument.Load("yourxmlfilepath");
            var lst = xml.Descendants("TP").ToList();
            XElement root = new XElement("MAIN");
            foreach (XElement xe in lst)
            {
                root.Add(xe);
            }
            root.Save(@"D:\myXMl.xml");

Saturday, November 1, 2014 11:36 AM

If you just want to use the root element. You can even rewrite the XML file using StreamWriter.

Add the line

sw.WriteLine("<MAIN");

before the first line then

sw.WriteLine("</MAIN>");

before the end of file.

http://chanmingman.wordpress.com/2013/06/25/read-and-write-a-text-file-using-c/

chanmm

chanmm


Saturday, November 1, 2014 11:43 AM

If you just want to use the root element. You can even rewrite the XML file using StreamWriter.

Add the line

sw.WriteLine("<MAIN");

before the first line then

sw.WriteLine("</MAIN>");

before the end of file.

http://chanmingman.wordpress.com/2013/06/25/read-and-write-a-text-file-using-c/

chanmm

chanmm

Except that'd give you:

<MAIN>
<?xml version="1.0"?>

Which won't work.

You'd have to substring the file or some such.


Saturday, November 1, 2014 1:07 PM

that was not i asked Andy..!