这是我的节目, 我正在使用STAX Parser来解析XML文档。 当我使用硬编码值时,只有它的工作(item.account =“sss”;) 但是如果我尝试使用的话 item.account = eventReader.getElementText(); List的大小为0 (List items = new ArrayList();)
import java.io.StringReader;
import java.util.*;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
public class Pavan {
static final String DATE = "date";
static final String ITEM = "item";
static final String MODE = "mode";
static final String UNIT = "unit";
static final String CURRENT = "current";
static final String INTERACTIVE = "interactive";
@SuppressWarnings({ "unchecked", "null" })
public static void main(String args[]) {
List<Position> items = new ArrayList<Position>();
try {
String documentAsString = "<request>\r\n" + "<accountid>1234</accountid>\r\n" + "<accountid>234</accountid>\r\n" + "</request>";
StringReader stringReadertext = new StringReader(documentAsString);
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader reader = inputFactory.createXMLStreamReader(stringReadertext);
XMLEventReader eventReader = inputFactory.createXMLEventReader(reader);
Position item = null;
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
StartElement startElement = event.asStartElement();
if (startElement.getName().toString().equals("accountid")) {
item = new Position();
item.account = "sss";
//item.account = eventReader.getElementText();
}
}
// If we reach the end of an item element we add it to the list
if (event.isEndElement()) {
EndElement endElement = event.asEndElement();
if (endElement.getName().toString().equals("accountid")) {
items.add(item);
}
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
}
System.out.println(items.size());
}
}
class Position
{
String account ;
}
答案 0 :(得分:2)
因为您的结束事件被“吃掉”而且if(event.isEndElement())从未被触发过。但是,当您进行硬编码时,由于缺少“eventReader.getElementText()”而触发了“if(event.isEndElement())”。
答案 1 :(得分:1)
我相信getElementText()
正在消耗结束事件,因此永远不会输入第二个if块。该方法的文档有点令人困惑。