Question

I am using this code to write a (simple) DOM tree to a string, but on my LG Optimus L3, this takes up to 30 seconds or more. How could I make 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();
Was it helpful?

Solution

I ended up just writing my own serializer. It certainly doesn't 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 a Document like this:

StringWriter writer = new StringWriter();
String result;

write(doc.getDocumentElement(), writer);
result = writer.getBuffer().toString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top