Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting xml string from Document in Java

Tags:

java

xml

I have a Java program aiming to consider an xml dom and write it into a string. I am using these packages: org.w3c.dom.* and javax.xml.parsers.*;

So I have DocumentBuilder, Document, Element objects...

Is there a way to get the string representing my xml dom in one call????

like image 288
Andry Avatar asked Jan 25 '11 13:01

Andry


People also ask

Can we convert XML to string in Java?

Java Code to Convert an XML Document to String For converting the XML Document to String, we will use TransformerFactory , Transformer and DOMSource classes. "</BookStore>"; //Call method to convert XML string content to XML Document object.

How do I convert a file to string in Java?

Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion. String convertDocumentToString(Document doc) : This method will take input as Document and convert it to String.

Which method converts the DOMDocument object into string?

DOMDocument implements the DOM API - access nodes via things like getElementById(), getElementsByClassName() , etc, and use saveXML() to write out a string.

What is the best way to parse XML in Java?

DOM Parser is the easiest java xml parser to learn. DOM parser loads the XML file into memory and we can traverse it node by node to parse the XML. DOM Parser is good for small files but when file size increases it performs slow and consumes more memory.


1 Answers

Its not one call but:

TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.METHOD, "xml");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));

StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc.getDocumentElement());

trans.transform(source, result);
String xmlString = sw.toString();

The setOutputProperty method makes the string output prettier so you can take it out.

like image 164
Grammin Avatar answered Nov 09 '22 16:11

Grammin