xpath - 通过 URL-Source 从 XML 文件中提取信息需要大量时间
问题描述
我想从 108 个 XML 文件中提取特定信息。一般来源也是一个 XML 文件,其中包含更多 URL 作为资源。 XML-Source 静态方法 getURL() 提取 URL,以便在 main 方法的 for 循环中将它们设置为 URL 路径。该程序有效,但它需要大约。5分钟从所有文件中获取数据。任何想法如何提高性能?
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
public class XmlReader2 {
public static void main(String[] args) throws IOException {
for (int i = 0; i < getURL().size(); i++) {
URL url = new URL(getURL().get(i));
try {
Document doc = new SAXBuilder().build(url);
final String getDeath = String
.format("//ns:teiHeader/ns:profileDesc/ns:particDesc/ns:listPerson/ns:person/ns:death");
XPathExpression<Element> xpath = XPathFactory.instance().compile(getDeath, Filters.element(), null,
Namespace.getNamespace("ns", "http://www.tei-c.org/ns/1.0"));
String test;
for (Element elem : xpath.evaluate(doc)) {
test = elem.getValue();
if (elem.getAttributes().size() != 0) {
test = elem.getAttributes().get(0).getValue();
}
System.out.println(elem.getName() + ": " + test);
}
} catch (org.jdom2.JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static List<String> getURL() throws IOException {
List<String> urlList = new ArrayList<>();
URL urlSource = new URL("http://www.steinheim-institut.de:80/cgi-bin/epidat?info=resources-mz1");
try {
Document doc = new SAXBuilder().build(urlSource);
final String getURL = String.format("/collection");
XPathExpression<Element> xpath = XPathFactory.instance().compile(getURL, Filters.element());
int i = 0;
for (Element elem : xpath.evaluate(doc)) {
while (i != elem.getChildren().size()) {
String url = elem.getChildren().get(i).getAttributes().get(1).getValue();
// System.out.println(url);
urlList.add(url);
i++;
}
}
} catch (org.jdom2.JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return urlList;
}
}
解决方案
从 Web 获取文件可能会导致此顺序的延迟。找一个工具来监控从你的机器发出的 HTTP 请求,看看发生了什么。特别注意对常见 W3C 文件(例如 XHTML DTD)的请求:因为这些文件经常被请求,W3C 故意在流程中注入延迟以鼓励人们使用文件的本地副本。如果事实证明这是问题所在,您可以使用多种技术来访问缓存的本地副本。
话虽如此,我对您的代码逻辑感到困惑。该方法getURL()
似乎在http://www.steinheim-institut.de:80/cgi-bin/epidat?info=resources-mz1
每次调用时都获取并解析文档,但您在循环中调用它,即使getURL().size()
用作终止条件。
推荐阅读
- java - 抽屉/侧边栏模板中无法识别 Android onclick 侦听器
- java - 在 Java 11 中映射泛型集合
- c# - 如何释放字典中对象使用的内存,还是不需要?
- javascript - 无法从允许未经身份验证的邮递员调用谷歌云功能
- python - 如何使用具有完整 I/O 的子进程从另一个脚本执行 Python 脚本?
- vba - MS Access VBA,试图更新一个表并从另一个表中删除
- debian - Debian 防火墙阻止 Minecraft 服务器端口
- python - Arthimatic 和 3D 数组中的组合 Numpy
- python - Python 2 与 Python 3 中的 sys.exc_info()
- javascript - 我的 REACT 应用程序出现路由问题