gpt4 book ai didi

java - 比 javax.xml.xpath 更快的 api 来解析 xml 的值?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:47:52 29 4
gpt4 key购买 nike

我正在使用 javax.xml.xpath 来搜索 xml 文件中的特定字符串,但是由于需要搜索的 xml 文件数量巨大,这比预期的。

是否有任何 java 支持的 api 比 javax.xml.xpath 更快或可用的最快?

最佳答案

正如 skaffman 指出的那样您需要确保尽可能高效地使用 javax.xml.xpath 库。如果您多次执行 XPath 语句,您需要确保将其编译成 XPathExpression

XPathExpression xPathExpression = xPath.compile("/root/device/modelname");
nl = (NodeList) xPathExpression.evaluate(dDoc, XPathConstants.NODESET);

演示

在示例中,选项 #2 将比选项 #1 更快。

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

public static void main(String[] args) {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = domFactory.newDocumentBuilder();
File xml = new File("input.xml");
Document dDoc = builder.parse(xml);

NodeList nl;

// OPTION #1
XPath xPath = XPathFactory.newInstance().newXPath();
nl = (NodeList) xPath.evaluate("root/device/modelname", dDoc, XPathConstants.NODESET);
printResults(nl);
nl = (NodeList) xPath.evaluate("/root/device/modelname", dDoc, XPathConstants.NODESET);
printResults(nl);

// OPTION #2
XPathExpression xPathExpression = xPath.compile("/root/device/modelname");
nl = (NodeList) xPathExpression.evaluate(dDoc, XPathConstants.NODESET);
printResults(nl);
nl = (NodeList) xPathExpression.evaluate(dDoc, XPathConstants.NODESET);
printResults(nl);
} catch (Exception e) {
e.printStackTrace();
}
}

private static void printResults(NodeList nl) {
for(int x=0; x<nl.getLength(); x++) {
System.out.println("the value is: " + nl.item(x).getTextContent());
}
}

}

输入.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
<blah>foo</blah>
<device>
<modelname>xbox</modelname>
</device>
<blah>bar</blah>
<device>
<modelname>wii</modelname>
</device>
<blah/>
</root>

关于java - 比 javax.xml.xpath 更快的 api 来解析 xml 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6471861/

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