9

How can I append an XML document to an xml node in c#?

5 Answers 5

15

An XmlDocument is basically an XmlNode, so you can append it just like you would do for any other XmlNode. However, the difference arises from the fact that this XmlNode does not belong to the target document, therefore you will need to use the ImportNode method and then perform the append.

// xImportDoc is the XmlDocument to be imported.
// xTargetNode is the XmlNode into which the import is to be done.

XmlNode xChildNode = xSrcNode.ImportNode(xImportDoc, true);
xTargetNode.AppendChild(xChildNode);
Sign up to request clarification or add additional context in comments.

3 Comments

ah yes, but what's xSrcNode? Why do I get the error message: Cannot import nodes of type 'Document'. What type is xTargetNode?
@fijiaaron You need to select the root element from the doc: XmlNode xChildNode = xSrcNode.ImportNode(xImportDoc.DocumentElement, true);
If your XmlDoc is currently typed as an XmlNode, or if you're trying to import an XmlNode you can instead do XmlNode xChildNode = xSrcNode.ImportNode(xImportDoc.OwnerDocument.DocumentElement, true);
6

Yes:

XmlNode imported = targetNode.OwnerDocument.ImportNode(otherDocument.DocumentElement, true);
targetNode.AppendChild(imported);

I think this creates a clone of your document though.

Comments

1

Perhaps like this:

XmlNode node = ......  // belongs to targetDoc (XmlDocument)

node.AppendChild(targetDoc.ImportNode(xmlDoc.DocumentElement));

Marc

2 Comments

AFAIK, you are required to *import a node if it doesn't belong to the current XmlDocument before you can append it. See my answer.
Yes, seems you need to call ImportNode indeed, but that will create a copy of the Xml document.....
1

Let's say you have the following construction:

The following structure is stored in an XmlElement named xmlElement:

</root>

and the following structure is stored in an XmlNode object named FooNode;

<foo>
    <bar>This is a test</bar>
    <baz>And this is another test</baz>
</foo>

Then you do the following:

XmlNode node = doc.ImportNode(FooNode.SelectSingleNode("foo"), true);
xmlElement.AppendChild(node);

Hope it helps someone

Comments

0

Once you have the root node of the XML document in question you can append it as a child node of the node in question. Does that make sense?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.