Stax处理XML,基于光标的查找,关键在于:
使用XMLInputFactory创建XMLStreamReader,获取了streamReader(光标)之后,(在while循环hasNext中)判断节点类型,是否为开始、结束、文本节点,之后根据情况进行处理。
/** * 基于光标的查找 * 输出节点名称和text值 */ @Test public void test01() { XMLInputFactory factory = XMLInputFactory.newInstance(); InputStream is = null; try { //输入流 is = TestStax.class.getClassLoader().getResourceAsStream("books.xml"); XMLStreamReader reader = factory.createXMLStreamReader(is); while(reader.hasNext()) { int type = reader.next(); //判断节点类型,是否为开始、结束、文本节点,之后根据情况进行处理 if (type == XMLStreamConstants.START_ELEMENT) { System.out.println(reader.getName()); } else if (type == XMLStreamConstants.CHARACTERS) { System.out.println(reader.getText().trim()); } else if (type == XMLStreamConstants.END_ELEMENT) { System.out.println("/" + reader.getName()); } } } catch (XMLStreamException e) { e.printStackTrace(); } finally { try { if(is != null) is.close(); } catch (IOException e) { e.printStackTrace(); } } }
输出结果:
bookstore
book
title
Everyday Italian
/title
author
Giada De Laurentiis
/author
year
2005
/year
price
30.00
/price
/book
book
...(此处省略)
/book
/bookstore
(2)测试二:输出属性,如果是book,就输出category
/** * 输出属性 * 如果是book,就输出category */ @Test public void test02() { XMLInputFactory factory = XMLInputFactory.newInstance(); InputStream is = null; try { is = TestStax.class.getClassLoader().getResourceAsStream("books.xml"); XMLStreamReader reader = factory.createXMLStreamReader(is); while(reader.hasNext()) { int type = reader.next(); if (type == XMLStreamConstants.START_ELEMENT) { String name = reader.getName().toString(); if (name.equals("book")) { System.out.println(reader.getAttributeName(0) + ": " + reader.getAttributeValue(0)); } } } } catch (XMLStreamException e) { e.printStackTrace(); } finally { try { if(is != null) is.close(); } catch (IOException e) { e.printStackTrace(); } } }
输出结果:
category: COOKING
category: CHILDREN
category: WEB
category: WEB
/** * 输出书的标题和价格 */ @Test public void test03() { XMLInputFactory factory = XMLInputFactory.newInstance(); InputStream is = null; try { is = TestStax.class.getClassLoader().getResourceAsStream("books.xml"); XMLStreamReader reader = factory.createXMLStreamReader(is); while(reader.hasNext()) { int type = reader.next(); if (type == XMLStreamConstants.START_ELEMENT) { String name = reader.getName().toString(); if (name.equals("title")) { System.out.print(reader.getElementText() + ": "); } if (name.equals("price")) { System.out.print(reader.getElementText() + "\n"); } } } } catch (XMLStreamException e) { e.printStackTrace(); } finally { try { if(is != null) is.close(); } catch (IOException e) { e.printStackTrace(); } } }
输出结果:
Everyday Italian: 30.00 Harry Potter: 29.99 XQuery Kick Start: 49.99 Learning XML: 39.95