新建xml文件(
users.xml):
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<users>
<user id="u1">
<address>
<address>海淀</address>
</address>
<nickname>张三</nickname>
<username>zhangsan</username>
</user>
<user id="u2">
<address>
<address>朝阳</address>
</address>
<nickname>李四</nickname>
<username>lisi</username>
</user>
</users>
XMLStreamReader读取xml文件:
/**
** XMLStreamConstants.START_ELEMENT = 1;
** XMLStreamConstants.CHARACTERS =4;
* XMLStreamConstants.END_ELEMENT = 2;
**/
XMLInputFactory factory = XMLInputFactory.newFactory();
InputStream stream = XmlInputFactory.
class.getClassLoader()
.getResourceAsStream("web
Service/xml/users.xml");
XMLStreamReader reader = factory.createXMLStreamReader(stream);
while (reader.
hasNext()) {
int type = reader.next();
if (type == XMLStreamConstants.START_ELEMENT) { // 开始节点
String name = reader.getName().toString();
if (name.equals("user")) {
System.out.print(reader.getAttributeValue(0) + ":");
}
if (name.equals("nickname")) {
System.out.println(reader.getElementText());
}
}
}