XMLStreamReader读取xml文件_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > XMLStreamReader读取xml文件

XMLStreamReader读取xml文件

 2014/6/27 21:29:17  xuweilovejava  程序员俱乐部  我要评论(0)
  • 摘要:新建xml文件(users.xml):<?xmlversion="1.0"encoding="UTF-8"standalone="yes"?><users><userid="u1"><address><address>海淀</address></address><nickname>张三</nickname><username>zhangsan</username>
  • 标签:文件 XML文件 XML
新建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("webService/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());
}
}
}
发表评论
用户名: 匿名