【发布时间】:2020-04-17 20:24:02
【问题描述】:
我有一个 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> ....(continue to have info about published books.)
从该文件中,我只想导出有关“年份”标签的详细信息。我试过这段代码:
public class Publications {
String year1="YEAR";
public static void main(String[] args) {
{
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean year = false;
//parser starts parsing a specific element inside the document
public void startElement(String uri, String localName, String year1 , Attributes attributes) throws SAXException {
System.out.println("Start Element :" + year1);
if (year1.equalsIgnoreCase("YEAR")) {
year = true;
}
}
//parser ends parsing the specific element inside the document
public void endElement(String uri, String localName, String year1) throws SAXException {
System.out.println("End Element:" + year1);
}
//reads the text value of the currently parsed element
public void characters(char ch[], int start, int length) throws SAXException {
if (year) {
System.out.println("Year : " + new String(ch, start, length));
year = false;
}
}
};
saxParser.parse("dblp-2020-04-01.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
我得到的结果不是我所期望的。它从包括年份标签在内的所有标签中导出更多详细信息。
Start Element :ee
End Element:ee
End Element:phdthesis
Start Element :phdthesis
Start Element :author
End Element:author
Start Element :title
End Element:title
Start Element :year
Year : 1990
End Element:year (...)
是否有关于仅从“年份”标签导出详细信息的代码建议?
【问题讨论】:
-
你想只有最后三行吗?如果这是真的,那么您可以将打印代码放入 if 语句中。还是你期待别的?
-
@SMortezaSA 我只希望出现年份:1990 年以及之后的所有年份
-
那你为什么要打印
startElement和endElement?如果您不在这两个函数中打印,则只会出现Year : 1990。有什么问题? -
另外,以及@SMortezaSA 提到的(即注释掉你不想要的打印语句!),这段代码还有一个更微妙的问题:
characters()方法不能保证阅读一次通过标签的全部内容。请参阅文档here。 -
A
StringBuilder通常用于处理此问题。继续追加到字符串生成器,直到“结束元素”事件发生。对于诸如“1990”之类的短文本,您可能还可以 - 但对于较长的文本(例如概要),您可能只能使用上述代码获得部分数据。