I spent a few hours yesterday trying to copy nodes from one xml document to another. The problem is this - there is a transport tool that transport XML documents from one server to the other and it works well, however, if the XML document(s) is large say over 15mb the transport tool fails. While trying not to rewrite the code, I decided that the most efficient way to solve the problem is to split the xml file in multiple files (chunks).

The format of the document should remain the same and the 7 headers should be included in all chunks - so in other words, all I need to do is split the content. Anyway, I soon found out that my way of thinking does not always work. I thought that I could simply create a blank xml document and loop through the original and copy nodes from one to the other - No! Here is how to Import nodes from one xml document to another. ImportNode is the trick.

 

    // Empty formatted document with all the neccessary
    // headers that should be in all files
    XmlDocument doc = EmptyProductFeeder().doc;

    // Grab all the nodes from the original document that we will
    // like to split into chunks
    XmlNodeList xnl = feedDoc.SelectNodes("OpenEnvelope/Message");

    // Current position in the nodelist above
    int position = 1;

    //
    for (int i = 0; i < xnl.Count; i++)
    {
        XmlNode xNode = xnl[i];
        if (string.Compare(xNode.Name, "Message", true) == 0)
        {
            // This is the tricky part - you have to use ImportNode
            // to be able to get a node from one document to another
            XmlNode xn = doc.ImportNode(xNode, true);
            doc.SelectSingleNode("OpenEnvelope").AppendChild(xn);

            position++;
            if (position > MaxNodesCountPerFile)
            {
                // Continue here, etc.
            }
        }
    }