import java.io.FileInputStream; import java.io.FileNotFoundException; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; /** * Stax解析Xml * @author Administrator * */ public class StaxXmlUtils { private static XMLInputFactory factory; private static XMLStreamReader reader; static{ factory = XMLInputFactory.newInstance(); } public static void parseXml() throws FileNotFoundException, XMLStreamException{ FileInputStream fis = new FileInputStream("src/users.xml"); reader = factory.createXMLStreamReader(fis); // 遍历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(); } } // 列出所有用户的名称和年龄 public static void listAllAttrs() throws FileNotFoundException, XMLStreamException { FileInputStream fis = new FileInputStream("src/user.xml"); reader = factory.createXMLStreamReader(fis); try { while (reader.hasNext()) { // 跳过所有空白、注释或处理指令,到下一个START_ELEMENT int event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { if ("user".equalsIgnoreCase(reader.getLocalName())) { System.out.print("name:" + reader.getAttributeValue(null, "name")); System.out.print(";age:" + reader.getAttributeValue(null, "age")); System.out.println(";gender:" + reader.getAttributeValue(null, "gender")); } } } reader.close(); } catch (XMLStreamException e) { e.printStackTrace(); } } /** * 测试 * @param args * @throws FileNotFoundException * @throws XMLStreamException */ public static void main(String[] args) throws FileNotFoundException, XMLStreamException { listAllAttrs(); } }


1443251642 LV1
2022年12月19日
PaymentCodeSystem LV11
2022年8月4日
likaiyu
2021年7月31日
暂无贡献等级
329512801 LV28
2021年7月8日
张洪 LV1
2021年7月1日
迷瞪的一批 LV6
2021年3月2日
我是你唯一的执着 LV4
2020年6月16日
raccoonxx LV2
2020年6月4日
0312wangchen LV26
2019年10月31日
hubugai1 LV11
2018年8月28日