Java appending XML docs to existing docs
It's a bit tricky, but the following example runs:
public static void main(String[] args) { DocumentImpl doc1 = new DocumentImpl(); Element root1 = doc1.createElement("root1"); Element node1 = doc1.createElement("node1"); doc1.appendChild(root1); root1.appendChild(node1); DocumentImpl doc2 = new DocumentImpl(); Element root2 = doc2.createElement("root2"); Element node2 = doc2.createElement("node2"); doc2.appendChild(root2); root2.appendChild(node2); DocumentImpl doc3 = new DocumentImpl(); Element root3 = doc3.createElement("root3"); doc3.appendChild(root3); // root3.appendChild(root1); // Doesn't work -> DOMException root3.appendChild(doc3.importNode(root1, true)); // root3.appendChild(root2); // Doesn't work -> DOMException root3.appendChild(doc3.importNode(root2, true)); }
I know you got the issue solved already, but I still wanted to take a stab at this problem using the XOM library that I'm currently testing out (related to this question), and while doing that, offer a different approach than that of Andreas_D's answer.
(To simplify this example, I put your <alert-set>
and <weather-set>
into separate files, which I read into nu.xom.Document
instances.)
import nu.xom.*;[...]Builder builder = new Builder();Document alertDoc = builder.build(new File("src/xomtest", "alertset.xml"));Document weatherDoc = builder.build(new File("src/xomtest", "weatherset.xml"));Document mainDoc = builder.build("<DataSet><blank/><blank/></DataSet>", "");Element root = mainDoc.getRootElement();root.replaceChild( root.getFirstChildElement("blank"), alertDoc.getRootElement().copy());root.replaceChild( root.getFirstChildElement("blank"), weatherDoc.getRootElement().copy());
The key is to make a copy of the elements to be inserted into mainDoc
; otherwise you'll get a complain that "child already has a parent".
Outputting mainDoc now gives:
<?xml version="1.0" encoding="UTF-8"?><DataSet> <alert-set> <warning>National Weather Service...</warning> <start-date>5/19/2009</start-date> <end-date>5/19/2009</end-date> </alert-set> <weather-set> <chance-of-rain type="percent">31</chance-of-rain> <conditions>Partly Cloudy</conditions> <temperature type="Fahrenheit">78</temperature> </weather-set></DataSet>
To my delight, this turned out to be very straight-forward to do with XOM. It only took a few minutes to write this, even though I'm definitely not very experienced with the library yet. (It would have been even easier without the <blank/>
elements, i.e., starting with simply <DataSet></DataSet>
.)
So, unless you have compelling reasons for using only the standard JDK tools, I warmly recommend trying out XOM as it can make XML handling in Java much more pleasant.