0

我正在尝试使用 java 中的 xpath 对巨大的 XML 文件进行一些查询,这是我的代码:

         DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
         docBuilderFactory.setNamespaceAware(true);

         DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
         Document document = docBuilder.parse(new File("test.xml"));

         XPath xpath = XPathFactory.newInstance().newXPath();

         String xPath = "/*/*[@id='ABCD']/*/*";

         XPathExpression expr = xpath.compile(xPath);
         NodeList result = (NodeList)expr.evaluate(document, XPathConstants.NODESET);

代码的最后一行花了很多时间,我不知道为什么,没有这行程序在 1 秒内完成,在 40 秒内完成。我也试过 XOM,它也不起作用。在 java 中的巨大 XML 文件中进行更快查询的替代方法是什么?

4

1 回答 1

0

Use SAX, not DOM. Because SAX requires much less memory than DOM, because SAX does not construct an internal representation (tree structure) of the XML data, as a DOM does. Instead, SAX simply sends data to the application as it is read; your application can then do whatever it wants to do with the data it sees.

For details read.

http://docs.oracle.com/javase/tutorial/jaxp/sax/index.html

于 2013-06-22T06:16:17.290 回答