import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
public class StaxTest {
// 获得解析器
public static XMLStreamReader getStreamReader() {
// String xmlFile = StaxTest.class.getResource("/").getFile()+ "users.xml";
String xmlFile = "c:\\company.xml";
XMLInputFactory factory = XMLInputFactory.newInstance();
//XMLInputFactory factory = XMLInputFactory.newFactory(); // the all equal
try {
XMLStreamReader reader = factory.createXMLStreamReader(new FileReader(xmlFile));
return reader;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}
return null;
}
// 列出所有用户名称
public static void listNames() {
XMLStreamReader reader = StaxTest.getStreamReader();
// 遍历XML文档
try {
while (reader.hasNext()) {
int event = reader.next();
// 如果是元素的开始
if (event == XMLStreamConstants.START_ELEMENT) {
// 列出所有用户名称
if ("user".equalsIgnoreCase(reader.getLocalName())) {
System.out.println("Name:" + reader.getAttributeValue(null,"name"));
}
}
}
reader.close();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("**********Start****************");
StaxTest.listNames();
System.out.println("**********End****************");
}
} 解析的文件:company.xml <?xml version="1.0" encoding="UTF-8"?> <company> <depart title="Develop Group"> <user name="Tom" age="28" gender="male" >Manager</user> <user name="Lily" age="26" gender="female" /> </depart> <depart title="Test Group"> <user name="Frank" age="32" gender="male" >Team Leader</user> <user name="Bob" age="45" gender="male" /> <user name="Kate" age="25" gender="female" /> </depart> </company>
原文链接:https://www.f2er.com/xml/299333.html