Link to home
Start Free TrialLog in
Avatar of eric0213
eric0213

asked on

XmlNode array to XmlDocument

I have an array of XmlNodes that I want to put into an XmlDocument so I can parse through them easily and save the XML file.

Suggestions?
Avatar of ozymandias
ozymandias
Flag of United Kingdom of Great Britain and Northern Ireland image

Create an XMLDocument.
Add a root element (called root ?).
Loop through your array and add the nodes to the root as children.
Avatar of eric0213
eric0213

ASKER

But what about the childnodes that have childnodes of their own?  I can write a recursive function to do this, but I thought there might be an easier way of doing this.

Something like
XmlDocument x = New XmlDocument();
x.AddNode("root");
x.ChildNodes = arrXmlNodes;

But this doesn't work, so I was hoping for somethign similar, something built-in.
using System;
using System.Xml;

class XMLTest2{

      public static void Main(string[] args){

            // create dummy document where we originally got our nodes from
            XmlDocument doc1 = new XmlDocument();
            // create an array6 to hold our nodes
            XmlNode[] nodes = new XmlNode[10];
            for (int i = 0; i < 10; i++){
                  nodes[i] = doc1.CreateElement("node" + i.ToString());
            }

            // now we create a document to add the nodes to
            XmlDocument doc2 = new XmlDocument();
            // preload it with a root element
            doc2.LoadXml("<root/>");
            // get a reference to the root element
            XmlNode root = doc2.DocumentElement;
            //loop through the array and add the nodes to the root having imported them into the document context
            for (int i = 0; i < 10; i++){
                  root.AppendChild(doc2.ImportNode(nodes[i],true));
            }
            Console.WriteLine(root.OuterXml);

      }


}
ASKER CERTIFIED SOLUTION
Avatar of ozymandias
ozymandias
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Excellent!  I'll give this a try when I get home from work and let you know how it goes.

Thanks
I haven't tested the solution because I ran into another problem.  Let's just assume your solution works.  If not, I'll come knocking.

Thanks again for your help.
Eric
Did you ever get this working ?
Can you grade this question now ?
Thanks :)