溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java Stax如何實(shí)現(xiàn)解析XML

發(fā)布時(shí)間:2020-10-30 23:20:11 來(lái)源:億速云 閱讀:161 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

這篇文章運(yùn)用簡(jiǎn)單易懂的例子給大家介紹Java Stax如何實(shí)現(xiàn)解析XML,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

package org.itat.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.FactoryConfigurationError;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
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 {

  @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();
        //判斷節(jié)點(diǎn)類型是否是開(kāi)始或者結(jié)束或者文本節(jié)點(diǎn),之后根據(jù)情況及進(jìn)行處理
        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();
      }
    }
  }
  
  @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();
      }
    }
  }
  
  @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();
      }
    }
  }
  
  @Test
  public void test04() {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    InputStream is = null;
    try {
      is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
      //基于迭代模型的操作方式
      XMLEventReader reader = factory.createXMLEventReader(is);
      int num = 0;
      while(reader.hasNext()) {
        //通過(guò)XMLEvent來(lái)獲取是否是某種節(jié)點(diǎn)類型
        XMLEvent event = reader.nextEvent();
        if(event.isStartElement()) {
          //通過(guò)event.asxxx轉(zhuǎn)換節(jié)點(diǎn)
          String name = event.asStartElement().getName().toString();
          if(name.equals("title")) {
            System.out.print(reader.getElementText()+":");
          }
          if(name.equals("price")) {
            System.out.print(reader.getElementText()+"\n");
          }
        }
        num++;
      }
      System.out.println(num);
    } catch (XMLStreamException e) {
      e.printStackTrace();
    } finally {
      try {
        if(is!=null) is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  
  @Test
  public void test05() {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    InputStream is = null;
    try {
      is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
      //基于Filter的過(guò)濾方式,可以有效的過(guò)濾掉不用進(jìn)行操作的節(jié)點(diǎn),效率會(huì)高一些
      XMLEventReader reader = factory.createFilteredReader(factory.createXMLEventReader(is),
          new EventFilter() {
            @Override
            public boolean accept(XMLEvent event) {
              //返回true表示會(huì)顯示,返回false表示不顯示
              if(event.isStartElement()) {
                String name = event.asStartElement().getName().toString();
                if(name.equals("title")||name.equals("price"))
                  return true;
              }
              return false;
            }
          });
      int num = 0;
      while(reader.hasNext()) {
        //通過(guò)XMLEvent來(lái)獲取是否是某種節(jié)點(diǎn)類型
        XMLEvent event = reader.nextEvent();
        if(event.isStartElement()) {
          //通過(guò)event.asxxx轉(zhuǎn)換節(jié)點(diǎn)
          String name = event.asStartElement().getName().toString();
          if(name.equals("title")) {
            System.out.print(reader.getElementText()+":");
          }
          if(name.equals("price")) {
            System.out.print(reader.getElementText()+"\n");
          }
        }
        num++;
      }
      System.out.println(num);
    } catch (XMLStreamException e) {
      e.printStackTrace();
    } finally {
      try {
        if(is!=null) is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  
  @Test
  public void test06() {
    InputStream is = null;
    try {
      is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
      //創(chuàng)建文檔處理對(duì)象
      DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      //通過(guò)DocumentBuilder創(chuàng)建doc的文檔對(duì)象
      Document doc = db.parse(is);
      //創(chuàng)建XPath
      XPath xpath = XPathFactory.newInstance().newXPath();
      //第一個(gè)參數(shù)就是xpath,第二參數(shù)就是文檔
      NodeList list = (NodeList)xpath.evaluate("//book[@category='WEB']", doc,XPathConstants.NODESET);
      for(int i=0;i<list.getLength();i++) {
        //遍歷輸出相應(yīng)的結(jié)果
        Element e = (Element)list.item(i);
        System.out.println(e.getElementsByTagName("title").item(0).getTextContent());
      }
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    } finally {
      try {
        if(is!=null) is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  
  @Test
  public void test07() {
    try {
      XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
      xsw.writeStartDocument("UTF-8","1.0");
      xsw.writeEndDocument();
      String ns = "http://11:dd";
      xsw.writeStartElement("nsadfsadf","person",ns);
      xsw.writeStartElement(ns,"id");
      xsw.writeCharacters("1");
      xsw.writeEndElement();
      xsw.writeEndElement();
      xsw.flush();
      xsw.close();
    } catch (XMLStreamException e) {
      e.printStackTrace();
    } catch (FactoryConfigurationError e) {
      e.printStackTrace();
    }
  }
  
  @Test
  public void test08() {
    InputStream is = null;
    try {
      is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
      //創(chuàng)建文檔處理對(duì)象
      DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      //通過(guò)DocumentBuilder創(chuàng)建doc的文檔對(duì)象
      Document doc = db.parse(is);
      //創(chuàng)建XPath
      XPath xpath = XPathFactory.newInstance().newXPath();
      Transformer tran = TransformerFactory.newInstance().newTransformer();
      tran.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
      tran.setOutputProperty(OutputKeys.INDENT, "yes");
      //第一個(gè)參數(shù)就是xpath,第二參數(shù)就是文檔
      NodeList list = (NodeList)xpath.evaluate("//book[title='Learning XML']", doc,XPathConstants.NODESET);
      //獲取price節(jié)點(diǎn)
      Element be = (Element)list.item(0);
      Element e = (Element)(be.getElementsByTagName("price").item(0));
      e.setTextContent("333.9");
      Result result = new StreamResult(System.out);
      //通過(guò)tranformer修改節(jié)點(diǎn)
      tran.transform(new DOMSource(doc), result);
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    } finally {
      try {
        if(is!=null) is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
<&#63;xml version="1.0" encoding="UTF-8"&#63;>

<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">XQuery Kick Start</title>
 <author>James McGovern</author>
 <author>Per Bothner</author>
 <author>Kurt Cagle</author>
 <author>James Linn</author>
 <author>Vaidyanathan Nagarajan</author>
 <year>2003</year>
 <price>49.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>

關(guān)于Java Stax如何實(shí)現(xiàn)解析XML就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI