有人可以告诉我为什么我在ArrayList中只有一个元素被称为items。 解析XML时,只有一个元素被添加到anrraylis。 这是我的代码
还
if (startElement.getName().toString().equals("accountid")){
pos.account =
}
正如你所看到的,已经有了
import java.io.FileNotFoundException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class StaXParser {
@SuppressWarnings({ "unchecked", "null" })
public static void main(String args[]) {
List<Position> items = new ArrayList<Position>();
try {
String documentAsString = "<request>\r\n" + "<accountid>12333</accountid>\r\n" + "<accountid>123</accountid>\r\n" + "</request>";
StringReader stringReadertext = new StringReader(documentAsString);
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader reader = inputFactory.createXMLStreamReader(stringReadertext);
XMLEventReader eventReader = inputFactory.createXMLEventReader(reader);
Position pos = null;
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
StartElement startElement = event.asStartElement();
if (startElement.getName().toString().equals("request"))
pos = new Position();
if (startElement.getName().toString().equals("accountid")) {
// System.out.println("yes");
pos.account = eventReader.getElementText().toString();
System.out.println("first" + pos.account);
}
if (startElement.getName().toString().equals("userid"))
pos.accountType = eventReader.getElementText(); // Mapped
// to
// userid
}
if (event.isEndElement()) {
EndElement endElement = event.asEndElement();
if (endElement.getName().toString().equals("request")) {
// System.out.println("also");
items.add(pos);
}
}
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
// System.out.println("ssssssss");
Position posss = (Position) itr.next();
System.out.println(posss.account);
}
}
catch (XMLStreamException e) {
e.printStackTrace();
}
}
}