Stax解析XML示例代码
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();
//判断节点类型是否是开始或者结束或者文本节点,之后根据情况及进行处理
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()) {
//通过XMLEvent来获取是否是某种节点类型
XMLEvent event = reader.nextEvent();
if(event.isStartElement()) {
//通过event.asxxx转换节点
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的过滤方式,可以有效的过滤掉不用进行操作的节点,效率会高一些
XMLEventReader reader = factory.createFilteredReader(factory.createXMLEventReader(is),
new EventFilter() {
@Override
public boolean accept(XMLEvent event) {
//返回true表示会显示,返回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()) {
//通过XMLEvent来获取是否是某种节点类型
XMLEvent event = reader.nextEvent();
if(event.isStartElement()) {
//通过event.asxxx转换节点
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");
//创建文档处理对象
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//通过DocumentBuilder创建doc的文档对象
Document doc = db.parse(is);
//创建XPath
XPath xpath = XPathFactory.newInstance().newXPath();
//第一个参数就是xpath,第二参数就是文档
NodeList list = (NodeList)xpath.evaluate("//book[@category='WEB']", doc,XPathConstants.NODESET);
for(int i=0;i<list.getLength();i++) {
//遍历输出相应的结果
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");
//创建文档处理对象
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//通过DocumentBuilder创建doc的文档对象
Document doc = db.parse(is);
//创建XPath
XPath xpath = XPathFactory.newInstance().newXPath();
Transformer tran = TransformerFactory.newInstance().newTransformer();
tran.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
tran.setOutputProperty(OutputKeys.INDENT, "yes");
//第一个参数就是xpath,第二参数就是文档
NodeList list = (NodeList)xpath.evaluate("//book[title='Learning XML']", doc,XPathConstants.NODESET);
//获取price节点
Element be = (Element)list.item(0);
Element e = (Element)(be.getElementsByTagName("price").item(0));
e.setTextContent("333.9");
Result result = new StreamResult(System.out);
//通过tranformer修改节点
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();
}
}
}
}
<?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">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>
Stax解析XML示例代码的更多相关文章
- [置顶] stax解析xml文档的6种方式
原文链接:http://blog.csdn.net/u011593278/article/details/9745271 stax解析xml文档的方式: 基于光标的查询: 基于迭代模型的查找: 基于过 ...
- webservice04#对象与xml转换-jaxb#Stax解析xml#新建修改xml
1,Student类 package com.yangw.xml; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement / ...
- [转载] 使用StAX解析xml
StAX 概述 从一开始,Java API for XML Processing (JAXP) 就提供了两种方法来处理 XML:文档对象模型(DOM)方法是用标准的对象模型表示 XML 文档:Simp ...
- MsXml创建和解析XML示例
一.MsXml创建XML文档示例 // XmlCreationDemo.cpp #include <stdlib.h> #include <stdio.h> // 引入MSXM ...
- python 解析XML python模块xml.dom解析xml实例代码
分享下python中使用模块xml.dom解析xml文件的实例代码,学习下python解析xml文件的方法. 原文转自:http://www.jbxue.com/article/16587.html ...
- Android DOM解析XML示例程序
DOM方式解析xml是先把xml文档都读到内存中,然后再用DOM API来访问树形结构,并获取数据的.DOM比较符合人的思维模式,但是其对内存的消耗比较大. activity_main.xml < ...
- 官方XmlPullParser和网络解析xml示例及详述
Parsing XML Data This lesson teaches you to Choose a Parser Analyze the Feed Instantiate the Parser ...
- 基于Woodstox的StAX 2 (Streaming API for XML)解析XML
StAX (Streaming API for XML)面向流的拉式解析XML,速度快.占用资源少,非常合适处理大数据量的xml文件. 详细教程和说明可以参见以下几篇文章: 使用 StAX 解析 XM ...
- JAVA解析xml的四种方式比较
1)DOM解析 DOM是html和xml的应用程序接口(API),以层次结构(类似于树型)来组织节点和信息片段,映射XML文档的结构,允许获取 和操作文档的任意部分,是W3C的官方标准 [优点] ①允 ...
随机推荐
- Java——final代码块是否一定被执行---18.11.08
辨析:final语句块一定会被执行吗? 答案是 不一定!!! 至少有两种情况下finally语句是不会被执行的: (1)try语句没有被执行到,如在try语句之前return就返回了,这样final语 ...
- jquery table 发送两次请求 解惑
版本1.10 以下链接为一个较低版本解决方案: http://blog.csdn.net/anmo/article/details/17083125 而我的情况有点作, 情况描述: 1,一个页面两个t ...
- React Router 4.0 实现路由守卫
在使用 Vue 或者 Angular 的时候,框架提供了路由守卫功能,用来在进入某个路有前进行一些校验工作,如果校验失败,就跳转到 404 或者登陆页面,比如 Vue 中的 beforeEnter 函 ...
- MapWindow介绍
官方网站:http://www.mapwindow.org/ 网站里包含了几个开源项目 目前最新版本是Mapwindow5,之前的mapwindow4版本已经停止更新,同时Mapwindow5底层是调 ...
- fastjson处理json
返回主页 你是风儿 博客园首页新随笔联系订阅管理 随笔 - 29 文章 - 0 评论 - 23 FastJson对于JSON格式字符串.JSON对象及JavaBean之间的相互转换 fastJson对 ...
- oradebug 的学习 一
说明 oradebug主要是给oracle支持人员使用的,尽管很早便有,但oracle官网很少有记载.他是个sql*plus命令行工具,有sysdba的权限就可以登入,无需特别设置.他可以被用 ...
- mysql新手进阶01
生活不止眼前的苟且,还有诗和远方. 请根据给出的数据库表结构来回答相应问题: DEPT (DEPTNO INT, DNAME VARCHAR(14),LOC VARCHAR(13)); EMP (EM ...
- lesson 15 Fifty pence worth of trouble
lesson 15 Fifty pence worth of trouble appreciate =be grateful for We really appreciate all the help ...
- [JSON].connectionValue()
语法: [JSON].connectionValue() 说明: 将对象的所有键值接连成新的字符串值 返回: [String] 示例: Set a = toJson() c = Array(1,2,3 ...
- sparkML原始数据转换成label-features方法
数据1:kaggle-旧金山犯罪分类数据 格式如下: Dates,Category,Descript,DayOfWeek,PdDistrict,Resolution,Address,X,Y -- :: ...