For what it's worth, here's a solution I came up with using the dom4j library. (I did check that it works.)
Read the XML fragment into a org.dom4j.Document
(note: all the XML classes used below are from org.dom4j; see Appendix):
String newNode = "<node>value</node>"; // Convert this to XML
SAXReader reader = new SAXReader();
Document newNodeDocument = reader.read(new StringReader(newNode));
Then get the Document into which the new node is inserted, and the parent Element (to be) from it. (Your org.w3c.dom.Document would need to be converted to org.dom4j.Document here.) For testing purposes, I created one like this:
Document originalDoc =
new SAXReader().read(new StringReader("<root><given></given></root>"));
Element givenNode = originalDoc.getRootElement().element("given");
Adding the new child element is very simple:
givenNode.add(newNodeDocument.getRootElement());
Done. Outputting originalDoc
now yields:
<?xml version="1.0" encoding="utf-8"?>
<root>
<given>
<node>value</node>
</given>
</root>
Appendix: Because your question talks about org.w3c.dom.Document
, here's how to convert between that and org.dom4j.Document
.
// dom4j -> w3c
DOMWriter writer = new DOMWriter();
org.w3c.dom.Document w3cDoc = writer.write(dom4jDoc);
// w3c -> dom4j
DOMReader reader = new DOMReader();
Document dom4jDoc = reader.read(w3cDoc);
(If you'd need both kind of Document
s regularly, it might make sense to put these in neat utility methods, maybe in a class called XMLUtils
or something like that.)
Maybe there are better ways to do this, even without any 3rd party libraries. But out of the solutions presented so far, in my view this is the easiest way, even if you need to do the dom4j <-> w3c conversions.
Update (2011): before adding dom4j dependency to your code, note that it is not an actively maintained project, and has some other problems too. Improved version 2.0 has been in the works for ages, but there's only an alpha version available. You may want to consider an alternative, like XOM, instead; read more in the question linked above.