gpt4 book ai didi

java - 大文件的 Xpath 方法

转载 作者:行者123 更新时间:2023-11-29 08:07:22 24 4
gpt4 key购买 nike

您现在将要看到的类是在 Java 中通过 XPath 解析 XML 文档的经典方法:

public class Main {

private Document createXMLDocument(String fileName) throws Exception {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(fileName);

return doc;
}

private NodeList readXMLNodes(Document doc, String xpathExpression) throws Exception {
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile(xpathExpression);

Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;

return nodes;
}

public static void main(String[] args) throws Exception {
Main m = new Main();
Document doc = m.createXMLDocument("tv.xml");
NodeList nodes = m.readXMLNodes(doc, "//serie/eason/@id");
int n = nodes.getLength();

Map<Integer, List<String>> series = new HashMap<Integer, List<String>>();

for (int i = 1; i <= n; i++) {
nodes = m.readXMLNodes(doc, "//serie/eason[@id='" + i + "']/episode/text()");
List<String> episodes = new ArrayList<String>();
for (int j = 0; j < nodes.getLength(); j++) {
episodes.add(nodes.item(j).getNodeValue());
}
series.put(i, episodes);
}

for (Map.Entry<Integer, List<String>> entry : series.entrySet()) {
System.out.println("Season: " + entry.getKey());
for (String ep : entry.getValue()) {
System.out.println("Episodio: " + ep);
}
System.out.println("+------------------------------------+");
}
}
}

在那里,我发现一些方法在处理巨大的 xml 文件时会令人担忧。喜欢使用

Document doc = builder.parse(fileName);

return doc;

  Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;

return nodes;

我很担心,因为我需要处理的 xml 文档是由客户创建的,在里面你基本上可以有无限数量的记录来描述电子邮件及其内容(每个用户都有自己的个人电子邮件,所以很多 html那里)。我知道这不是最明智的方法,但它是一种可能性,而且在我到达这里之前它已经启动并运行。

我的问题是:如何使用 xpath 解析评估 巨大的 xml 文件?

最佳答案

您可以使用 StAX 解析器。它将比 DOM 选项占用更少的内存。关于 StAX 的一个很好的介绍在 http://tutorials.jenkov.com/java-xml/stax.html

关于java - 大文件的 Xpath 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10267284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com