public static void test04() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//基于迭代模型的操作方式
XMLEventReader reader = factory.createXMLEventReader(is);
int num = 0;
while(reader.hasNext()) {
//通过XMLEvent来获取是否是某种节点类型
XMLEvent event = reader.nextEvent();
if(event.isStartElement()) {
//通过event.asxxx转换节点
String name = event.asStartElement().getName().toString();
if(name.equals("title")) {
System.out.print(reader.getElementText()+":");
}
if(name.equals("price")) {
System.out.print(reader.getElementText()+"\n");
}
}
num++;
}
System.out.println(num);
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}