「Java入門」StAXでXMLを処理するサンプル

1.xmlコード
<?xml version="1.0″ encoding="UTF-8″?>
<data>
aaa<name>admin</name>bbb
ccc<password>startnews24</password>ddd
</data>
2.Javaコード:
public static void main(String[] args) throws Exception {
InputStream in = new FileInputStream(
“D:\\startnews24Project\\tts_tuan\\src\\stax_test\\java\\com\\startnews24\\stax_test\\stax.xml");
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader parser = factory.createXMLStreamReader(in);
while (true) {
int event = parser.next();
if (event == XMLStreamConstants.END_DOCUMENT) {
parser.close();
break;
} else if (event == XMLStreamConstants.START_ELEMENT) {
System.out.println(parser.getLocalName());
} else if (event == XMLStreamConstants.CHARACTERS) {
System.out.println(parser.getText());
}else if (event == XMLStreamConstants.END_ELEMENT) {
System.out.println(parser.getLocalName());
}
}
}

Development

Posted by arkgame