0
Answer

Moving XML nodes from one file to another

Mark Turner

Mark Turner

16y
5.3k
1
I'm having difficulty importing nodes from one document to another. I want to move one node and all its children and append it to a node in the target document. When I run this code it gets as far as the second from last line, the importNode step and crashes citing "Cannot import Null node". My XML has the following layout in both files:

<root namespace.....>
<schema>
....//schema goes here
</schema>
<dataroot>
<dvd>
<id>####</id>
<title>########</title>
</dvd>
...//more records here
</dataroot>
</root>

Any help is much appreciated.

private void OnAddInputChanged(object sender, EventArgs e)

{

string add = addValue.Value;// Get the user input value

string library = DataDirectory + "Library.xml";//create full path to library file

string fileName = add + ".xml"; //create filename ([UserInput].xml)

string source = DataDirectory + fileName;//create full path to newly added file

XmlDocument docLibrary = new XmlDocument();

docLibrary.Load(library);
//load library

XmlDocument docSource = new XmlDocument();

docSource.Load(source);
//load new file

XmlNamespaceManager nsmgrLibrary = new XmlNamespaceManager(docLibrary.NameTable);

nsmgrLibrary.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
//add namespace

XmlNamespaceManager nsmgrNew = new XmlNamespaceManager(docSource.NameTable);

nsmgrNew.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
//add namespace

XmlNode newNode= docSource.SelectSingleNode("//xsd:dataroot/DVD", nsmgrNew);
//load first node from new file

XmlNode libraryRoot = docLibrary.DocumentElement;
//get root element of library file

XmlNode importNewNode = docLibrary.ImportNode(newNode, true);
//import new node

libraryRoot.AppendChild(importNewNode);
//append to the root node

}