(四)StAX流机制解析器
StAX 解析器时一种拉解析器(pull parser),与安装事件处理器不同,只需要使用基本的循环来迭代所有事件,示例代码如下:
try {
Path xmlPath = Paths.get("E://IDEA Workspace//exampleiostream//src//main//java//org//drsoft//examples//xml", "appParse.xml");
InputStream xmlStream = Files.newInputStream(xmlPath, StandardOpenOption.READ);
XMLInputFactory factory = XMLInputFactory.newFactory();
XMLStreamReader parser = factory.createXMLStreamReader(xmlStream);
while (parser.hasNext()) {
int event = parser.next();
switch (event) {
case XMLStreamConstants.START_DOCUMENT:
System.out.println("START_DOCUMENT Call");
break;
case XMLStreamConstants.END_DOCUMENT:
System.out.println("END_DOCUMENT Call");
break;
case XMLStreamConstants.START_ELEMENT:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parser.getAttributeCount(); i++) {
sb.append(parser.getAttributeName(i) + "=/"" + parser.getAttributeValue(i) + "/"");
}
System.out.println("START_ELEMENT qName=" + parser.getName() + " Uri="
+ parser.getNamespaceURI() + " localName=" + parser.getLocalName() + " attribute="
+ sb.toString());
break;
case XMLStreamConstants.END_ELEMENT:
System.out.println("END_ELEMENT qName=" + parser.getName() + " Uri=" + parser.getNamespaceURI()
+ " localName=" + parser.getLocalName());
break;
case XMLStreamConstants.CHARACTERS:
int start = parser.getTextStart();
int length = parser.getTextLength();
System.out.println("CHARACTERS text=" + new String(parser.getTextCharacters(), start, length));
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}