Wednesday, October 28, 2009

JDOM: String XML Tree to Element

Converting XML Tree in String to JDOM Element


There would be case that a given string that is in xml structure needs to be inserted into an existing DOM.
i.e.
<INFO>
<CREATED-BY>Someone</CREATED-BY>
<CREATED-DATE>YYYY-MM-DD HH24:MI:SS</CREATED-DATE>
</INFO>


For this scenario you need to use SaxBuilder and StringReader :
String str = "<INFO><CREATED-BY>Someone</CREATED-BY><CREATED-DATE>YYYY-MM-DD HH24:MI:SS</CREATED-DATE></INFO>";

StringReader reader = new StringReader(str);
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(reader);
Element element = document.getRootElement();



Now, you can have the element variable to be added as content to other Document

1 comment: