Javax.xml.transform.Transformer is very slow

I use this code to write a (simple) DOM tree to a string, but on my LG Optimus L3 it takes up to 30 seconds or more. How can I do it faster?

Transformer t = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); t.transform(new DOMSource(doc), new StreamResult(writer)); result = writer.getBuffer().toString(); 
0
source share
1 answer

In the end, I just wrote my own serializer. This, of course, does not support everything, just tag names, attributes and text content, but it is simple and fast:

 void write(Node e, StringWriter w) { if (e.getNodeType() == Node.ELEMENT_NODE) { w.write("<"+e.getNodeName()); if (e.hasAttributes()) { NamedNodeMap attrs = e.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { w.write(" "+attrs.item(i).getNodeName()+"=\""+ attrs.item(i).getNodeValue()+"\""); } } w.write(">"); if (e.hasChildNodes()) { NodeList children = e.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { write(children.item(i), w); } } w.write("</"+e.getNodeName()+">"); } if (e.getNodeType() == Node.TEXT_NODE) { w.write(e.getTextContent()); } } 

You use it with Document as follows:

 StringWriter writer = new StringWriter(); String result; write(doc.getDocumentElement(), writer); result = writer.getBuffer().toString(); 
0
source

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


All Articles