Sunday, March 22, 2009

Adding String of XML nodes to Document Node - JDom

Let's say you have a JDom XML Document and you have a string of XML content. You want to add the XML content in the String to a particular Node or Element in the Xml document. Here's how in a nutshell, though you'll probably want to organize these differently in the actual implementation.

1. Convert the XML String to XML as follows:

String s = "<nodes><node>one</node><node>two</node></nodes>"
SAXBuilder sb = new SAXBuilder();
InputStream is = IoTools.inputStreamFromString(s);
Document doc = sb.build(is);

2. Get the element you want to update

//assuming you have instantiated XML Document doc2Update elsewhere
String xpath="/some/node/in/document";
Element e = (Element) (XPath.selectSingleNode(doc2Update , xpath));

3. Add the document content to the element

e.addContent(doc.getRootElement().cloneContent());