使用Java中的BufferedReader解析XML

问题描述 投票:0回答:2

首先要使用XML文件2,84GB,而SAX或DOM解析器似乎都不起作用。我已经尝试过了,每次都崩溃了。因此,我选择使用BufferedReader读取文件并导出我想要的数据,解析XML文件,就像它是txt。

XML文件(小部分):

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp-2019-11-22.dtd">
<dblp>
<phdthesis mdate="2016-05-04" key="phd/dk/Heine2010">
<author>Carmen Heine</author>
<title>Modell zur Produktion von Online-Hilfen.</title>
<year>2010</year>
<school>Aarhus University</school>
<pages>1-315</pages>
<isbn>978-3-86596-263-8</isbn>
<ee>http://d-nb.info/996064095</ee>
</phdthesis><phdthesis mdate="2020-02-12" key="phd/Hoff2002">
<author>Gerd Hoff</author>
<title>Ein Verfahren zur thematisch spezialisierten Suche im Web und seine Realisierung im Prototypen HomePageSearch</title>
<year>2002</year>

[我想从该XML文件中检索标签<year>之间的数据。我还使用了Pattern和Matcher和regEx来查找所需的信息。到目前为止,我的代码:

public class Publications {
    public static void main(String[] args) throws IOException {
        File file = new File("dblp-2020-04-01.xml");
        FileInputStream fileStream = new FileInputStream(file);
        InputStreamReader input = new InputStreamReader(fileStream);
        BufferedReader reader = new BufferedReader(input);
        String line;
        String regex = "\\d+";


        // Reading line by line from the
        // file until a null is returned
        while ((line = reader.readLine()) != null) {
            final Pattern pattern = Pattern.compile("<year>(.+?)</year>", Pattern.DOTALL);
            final Matcher matcher = pattern.matcher("<year>"+regex+"</year>");
            matcher.find();
            System.out.println(matcher.group(1)); // Prints String I want to extract
            }
        }
}

编译后,结果不是我期望的。每次解析器找到...标记时,都无需打印确切的年份,结果如下:

\d+
\d+
\d+
\d+
\d+
\d+
\d+
\d+
\d+
\d+

有什么建议吗?

java xml parsing bufferedreader
2个回答
0
投票

备注

Regexen是从xml(或类似结构格式)提取信息的错误工具。不建议使用一般方法。对于正确的处理方式,请参见。迈克尔·凯的答案。

答案

您在构造匹配器时提供了错误的论点。您需要提供当前行,而不是代码中的表达式:

// ...
final Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
    System.out.println(matcher.group(1)); // Prints String I want to extract
}
// ...

请注意附加条件,以检查当前行是否完全匹配。

还请注意,您要匹配的模式是在Pattern构造函数中定义的。因此,为了仅匹配包含数字值的<year>标签,必须将该行更改为

final Pattern pattern = Pattern.compile("<year>(" + regex + ")</year>", Pattern.DOTALL);

1
投票

请不要尝试使用正则表达式解析XML。试图以特殊格式生成XML的人们在此论坛上收到数百个问题,因为这是接收应用程序可以处理的唯一事情,并且接收应用程序具有此类限制的原因是,它试图“手动”执行XML解析。 。您正在为自己,要与之交换数据的人员以及为StackOverflow上的人员存储麻烦,而当一切都陷入困境时,您将寻求帮助。 XML标准的存在是有原因的,当每个人都遵守它们时,它就会很好地工作。

在这种情况下,正确的方法是使用SAX,StAX或XSLT 3.0的XML流方法,而出于完全虚假的原因,您已经放弃了这些方法。

© www.soinside.com 2019 - 2024. All rights reserved.