0

我有一个将 xml 字符串发送到输出流的应用程序。在将内容写入输出流之前,我必须确保文本节点中的内容(节点值中的内容)不超过固定长度。为此,我编写了一个示例代码来获取文本节点内容,这可以帮助我进行内容验证。但我担心这个示例代码是有效的,因为当我运行它时它需要大约 0.2 秒 eclipse profiler(TPTP)。我想知道是否有更好的方法来提高性能。下面是示例代码。

 StringWriter stringWriter = new StringWriter();
     stringWriter.write("<node src='something'>nodetext goes here</node>");
     InputSource src = new InputSource(new StringReader(stringWriter.toString()));
     try {
        Element doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
        System.out.println(doc.getChildNodes().getLength());
        Node n = doc.getChildNodes().item(0);
        System.out.println(n.getNodeValue());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
4

2 回答 2

1

You will get a vast performance improvement by reusing the DocumentBuilderFactory - creating the factory involves searching the classpath. Reusing the DocumentBuilder will probably help as well. However, the overall approach of creating XML as a string, parsing it, and then serailizing it again seems intrinsically inefficient and I haven't really understood your explanation of why it's necessary.

于 2013-02-04T09:01:20.173 回答
0

使用 SAX 解析器而不是 DOM。有关示例,请参见本文。

于 2013-02-04T01:30:45.623 回答