javax.xml.transform.Transformer非常慢

时间:2014-05-08 13:49:24

标签: java android xml dom

我正在使用此代码将(简单)DOM树写入字符串,但在我的LG Optimus L3上,这需要30秒或更长时间。我怎么能让它更快?

Transformer t = TransformerFactory.newInstance().newTransformer();

transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
t.transform(new DOMSource(doc), new StreamResult(writer));
result = writer.getBuffer().toString();

1 个答案:

答案 0 :(得分:0)

我最后只是编写自己的序列化程序。它当然不支持所有内容,只是标记名称,属性和文本内容,但它简单而快速:

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());
    }
}

您可以像Document一样使用它:

StringWriter writer = new StringWriter();
String result;

write(doc.getDocumentElement(), writer);
result = writer.getBuffer().toString();