[ACCEPTED]-how to convert dom4j document object to string-dom4j

Accepted answer
Score: 10

asXml() return String from Document object

String text = document.asXML()


Score: 3

Why can't you just do:

String result = dom.toXML().toString();

If you want to do 7 it the long way, then you use a TransformerFactory to transform 6 the DOM to anything you want. First thing 5 you do is wrap your Document in a DOMSource

DOMSource domSource = new DOMSource(document);

Prepare 4 a StringWriter so we can route the stream to a String:

StringWriter writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);

Prepare 3 a TransformationFactory so you can transform the DOM to the source 2 provided:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory .newTransformer();
transformer.transform(domSource, streamResult);

Finally, you get the String:

String result = writer.toString();

Hope that 1 helped!

Score: 0

How can you have a non XML dom,

a Dom is 6 in essence an XML document,

asXml() returns 5 a string representation of the Dom , which 4 is XML,

if you need to pull just the text 3 values then you can iterate through the 2 dom and getValue() on elements but what 1 you are asking for seems to be the xml string,

More Related questions