XML 使用Stax 基于XPath 和XMLEventReader迭代模型 和过滤方式的解析

xml文件  放在src下

book.xml:

<?xml version="1.0" encoding="UTF-8"?>


<bookstore>
 
<book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>


<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>

 
<book category="WEB">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>

</bookstore>

 

 package xml.sg.stax;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.EventFilter;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class TestStax {
 // Stax解析xml
 @Test
 public void test01() {
  XMLInputFactory factory = XMLInputFactory.newInstance();
  InputStream stream = null;
  try {
   stream = TestStax.class.getClassLoader().getResourceAsStream(
     "book.xml");
   XMLStreamReader reader = factory.createXMLStreamReader(stream);
   while (reader.hasNext()) {
    int len = reader.next();
    // 判断是否是开始元素
    if (len == 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 {
   if (stream != null) {
    try {
     stream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

 @Test
 public void test02() {
  XMLInputFactory factory = XMLInputFactory.newInstance();
  InputStream stream = null;
  try {
   stream = TestStax.class.getClassLoader().getResourceAsStream(
     "book.xml");
   XMLStreamReader reader = factory.createXMLStreamReader(stream);
   while (reader.hasNext()) {
    int len = reader.next();
    // 判断是否是开始元素
    if (len == XMLStreamConstants.START_ELEMENT) {
     String name = reader.getName().toString();
     if (name.equals("title")) {
      System.out.println(reader.getElementText() + ":");
     }
     if (name.equals("price")) {
      System.out.println(reader.getElementText() + "/n");
     }
    }
   }
  } catch (XMLStreamException e) {
   e.printStackTrace();
  } finally {
   if (stream != null) {
    try {
     stream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

 @Test
 public void test03() {
  XMLInputFactory factory = XMLInputFactory.newInstance();
  InputStream stream = null;
  try {
   stream = TestStax.class.getClassLoader().getResourceAsStream(
     "book.xml");
   // 基于迭代模型操作
   XMLEventReader reader = factory.createXMLEventReader(stream);
   while (reader.hasNext()) {
    // 通过XMLEvent来获取是否是某种节点类型
    XMLEvent event = reader.nextEvent();
    // 判断是否是开始元素
    if (event.isStartElement()) {
     // 通过event.asxxx来转换节点
     String name = event.asStartElement().getName().toString();
     if (name.equals("title")) {
      System.out.println(reader.getElementText() + ":");
     }
     if (name.equals("price")) {
      System.out.println(reader.getElementText() + "/n");
     }
    }
   }
  } catch (XMLStreamException e) {
   e.printStackTrace();
  } finally {
   if (stream != null) {
    try {
     stream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

 @Test
 public void test04() {
  XMLInputFactory factory = XMLInputFactory.newInstance();
  InputStream stream = null;
  try {
   stream = TestStax.class.getClassLoader().getResourceAsStream(
     "book.xml");
   // 基于Filter的过滤方式 可以有效过滤掉不用进行操作的节点 效率更高一些
   XMLEventReader reader = factory.createFilteredReader(
     factory.createXMLEventReader(stream), new EventFilter() {
      @Override
      public boolean accept(XMLEvent event) {
       if (event.isStartElement()) {
        return true;
       }
       return false;
      }
     });
   while (reader.hasNext()) {
    // 通过XMLEvent来获取是否是某种节点类型
    XMLEvent event = reader.nextEvent();
    // 判断是否是开始元素
    if (event.isStartElement()) {
     // 通过event.asxxx来转换节点
     String name = event.asStartElement().getName().toString();
     if (name.equals("title")) {
      System.out.println(reader.getElementText() + ":");
     }
     if (name.equals("price")) {
      System.out.println(reader.getElementText() + "\n");
     }
    }
   }
  } catch (XMLStreamException e) {
   e.printStackTrace();
  } finally {
   if (stream != null) {
    try {
     stream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

 @Test
 public void test05() {
  InputStream stream = null;
  try {
   stream = TestStax.class.getClassLoader().getResourceAsStream(
     "book.xml");
   //创建文档处理对象
   DocumentBuilder builder = DocumentBuilderFactory.newInstance()
     .newDocumentBuilder();
   //通过DocumentBuilder创建文档对象
   Document document = builder.parse(stream);
   //创建XPath
   XPath xPath = XPathFactory.newInstance().newXPath();
   //第一个参数是xpath 第二个参数是文档 找category='WEB'的title
   NodeList nodeList = (NodeList) xPath.evaluate("//book[@category='WEB']", document,XPathConstants.NODESET);
   for (int i = 0; i < nodeList.getLength(); i++) {
    //遍历输入的相应结果
    Element element = (Element) nodeList.item(i);
    System.out.println(element.getElementsByTagName("title").item(0).getTextContent());
   }
   
  } catch (XPathExpressionException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  }
 }
}

 

 

 

你可能感兴趣的:(reader)