Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a simple way to convert my XML object back to String in java?

Tags:

java

xml

I have an xml document object that I need to convert into a string.

Is there as simple way to do this?

like image 299
Yevgeny Simkin Avatar asked Feb 03 '09 18:02

Yevgeny Simkin


1 Answers

Here's some quick code I pulled out of a library I had nearby. Might wanna dress it up, but it works:

import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public String TransformDocumentToString(Document doc)
{
    DOMSource dom = new DOMSource(doc);
    StringWriter writer = new StringWriter();  
    StreamResult result = new StreamResult(writer);

    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.transform(dom, result);

    return writer.toString();
} 

edit: as commentor noticed earlier, i had a syntax error. had to pull out some sensitive lines so I wouldn't get canned and put them back in the wrong order. thanks! ;-)

like image 67
joshua.ewer Avatar answered Nov 07 '22 05:11

joshua.ewer