Getting xml string from a document in Java

I have a Java program whose purpose is to examine the xml dom and write it to a string. I use these packages: org.w3c.dom.* And javax.xml.parsers.*;

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

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

+4
source share
4 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 more beautiful, so you can take it out.

+15
source
 String xmlString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc); 
+2
source

I am also looking for a cheap and efficient way to serialize the DOM. So far, I see only 2 options:

Perhaps you can try the LSSerializer approach (but not in a single call).

0
source

The org.apache.axis.utils.XMLUtils.PrettyDocumentToString (Document) method has a problem that includes spaces in tag values.

The solution uses the org.apache.axis.utils.XMLUtils.DocumentToString (Document) method.

0
source

Source: https://habr.com/ru/post/1336977/


All Articles