我正在寻找一种方法来获取标记内容后停止解析器。我怎样才能做到这一点?另外我怎么知道我现在正在搜索我的标签。
public class XmlParser {
public String getValue(final String xml, final String tag) throws XMLStreamException {
String tagContent = null;
final XMLInputFactory factory = XMLInputFactory.newInstance();
final XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(xml));
while (reader.hasNext()) {
final int event = reader.next();
switch (event) {
case XMLStreamConstants.START_ELEMENT:
break;
case XMLStreamConstants.CHARACTERS:
tagContent = reader.getText().trim();
break;
case XMLStreamConstants.END_ELEMENT:
break;
}
}
return tagContent;
}
}
答案 0 :(得分:1)
boolean finished = false;
while(!finished && reader.hasNext()) {
final int event = reader.next();
//set finished = true if you hit an event that means you want to stop parsing
}
//don't forget to close the reader and the I/O streams