9

Just trying to find a way to convert a Dom4J Document content to String. It has a asXML() API which converts the content to a XML. In my case,I'm editing a non-xml DOM structure using Dom4J and trying to convert the content to String. I know its possible in case of w3c document.

Any pointers will be appreciated.

Thanks

Shamik
  • 1,671
  • 11
  • 36
  • 64
  • 2
    Have you solved? Why `asXml()` doesn't work for you? I don't understand what you need, can you clarify your question please? – javanna Apr 11 '11 at 10:30

3 Answers3

12

asXml() return String from Document object

String text = document.asXML()
James
  • 456
  • 6
  • 14
3

Why can't you just do:

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

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

DOMSource domSource = new DOMSource(document);

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

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

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

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

Finally, you get the String:

String result = writer.toString();

Hope that helped!

Mohamed Mansour
  • 39,445
  • 10
  • 116
  • 90
  • He stated he wanted non-XML, though he didn't elaborate on what the desired format actually was. Your solution produces XML. – Alan Krueger Oct 18 '11 at 21:55
0

How can you have a non XML dom,

a Dom is in essence an XML document,

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

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

Theresa Forster
  • 1,914
  • 3
  • 19
  • 35