SAX Parser不显示多个相同的标记



以前,我可以显示一个标签的数据,但这次没有显示几个值,而是只显示一个。

这是我的解析器代码:

public class Runner {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
MyHandler handler = new MyHandler();
xmlReader.setContentHandler(handler);
xmlReader.parse("src/countries.xml");
Countries branches = handler.getBranches();
try (FileWriter files = new FileWriter("src/diploma/SAX.txt")) {
files.write("Item " + "n" + String.valueOf(branches.itemList) + "n");
}
}
private static class MyHandler extends DefaultHandler{
static final String HISTORY_TAG = "history";
static final String ITEM_TAG = "item";
static final String NAME_ATTRIBUTE = "name";
public Countries branches;
public Item currentItem;
private String currencyElement;
Countries getBranches(){
return branches;
}
public void startDocument() throws SAXException {
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
currencyElement = qName;
switch (currencyElement) {
case HISTORY_TAG: {
branches.itemList = new ArrayList<>();
currentItem = new Item();
currentItem.setHistoryName(String.valueOf(attributes.getValue(NAME_ATTRIBUTE)));
} break;
default: {}
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String text = new String(ch, start, length);
if (text.contains("<") || currencyElement == null){
return;
}
switch (currencyElement) {
case ITEM_TAG: {
currentItem.setItem(text);
} break;
default: { }
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException{
switch (qName) {
case HISTORY_TAG: {
branches.itemList.add(currentItem);
currentItem = null;
} break;
default: {
}
}
currencyElement = null;
}
public void endDocument() throws SAXException {
System.out.println("SAX parsing is completed...");
}
}
}

分类项目:

public class Item {
private String historyName;
private String item;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getHistoryName() {
return historyName;
}
public void setHistoryName(String historyName) {
this.historyName = historyName;
}
@Override
public String toString() {
return
"historyName = " + historyName + ", " + "n" + "item = " + item + ", ";
}
}

和阶级国家

public class Countries {
public List<Item> itemList;
} 

我对这个部件有问题

<history name="История">

<item>
История белорусских земель очень богата и самобытна. 
</item>

<item>
Эту страну постоянно раздирали внутренние конфликты и противоречия, много раз она была втянута в войны.
</item>

<item>
В 1945 году Беларусь вступила в состав членов-основателей Организации Объединенных Наций.
</item>

</history>

我只显示最后一个";项目";标签和其他重复标签仅以单数形式显示。我不知道错误在哪里,但我注意到在";endElement";所有值都显示出来,但作为一个元素。也许有人知道怎么回事?

每次遇到item标记时,都会创建一个新的ArrayList。这就是为什么解析后只显示一个项目的原因。

最新更新