-
Java操作XML(4)--使用woodstox处理XML
Woodstox是一个快速、开源的StAX实现;被视为执行效果最佳的StAX实现之一。本文主要介绍使用Woodstox来理XML,文中所使用到的软件版本:Java 1.8.0_191、woodstox-core-asl 4.4.1。
1、引入依赖
<dependency> <groupId>org.codehaus.woodstox</groupId> <artifactId>woodstox-core-asl</artifactId> <version>4.4.1</version> </dependency>
2、Woodstox例子
2.1、XML文件
<?xml version="1.0" encoding="utf-8" ?> <school:grade xmlns:school="http://www.w3.org/TR/html4/school/"> <school:student rollno="1" school:age="10"> <school:firstname>cxx1</school:firstname> <lastname>Bob1</lastname> <nickname>stars1</nickname> <marks>85</marks> </school:student> <student rollno="2"> <firstname>cxx2</firstname> <lastname>Bob2</lastname> <nickname>stars2</nickname> <marks>85</marks> </student> <student rollno="3"> <firstname>cxx3</firstname> <lastname>Bob3</lastname> <nickname>stars3</nickname> <marks>85</marks> </student> </school:grade>
2.2、Java代码例子
该例子演示如何使用Woodstox来解析XML以及使用Woodstox来生成XML。
package com.abc.demo.general.xml; import org.apache.commons.lang.StringUtils; import org.codehaus.stax2.*; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.namespace.QName; import javax.xml.stream.*; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.XMLEvent; import java.util.ArrayList; import java.util.List; /** * 使用Woodstox处理xml */ public class WoodstoxCase { private static Logger logger = LoggerFactory.getLogger(WoodstoxCase.class); /** * 基于光标的方式解析xml * @throws Exception */ @Test public void parse() throws Exception { XMLInputFactory2 factory = (XMLInputFactory2)XMLInputFactory2.newFactory(); XMLStreamReader2 reader = (XMLStreamReader2)factory.createXMLStreamReader(WoodstoxCase.class.getResourceAsStream("student.xml")); //添加过滤器 XMLStreamReader2 filterReader = (XMLStreamReader2)factory.createFilteredReader(reader, new StreamFilter() { @Override public boolean accept(XMLStreamReader reader) { if (reader.isStartElement() || reader.isEndElement() || reader.isCharacters()) { return true; } return false; } }); List<Student> students = new ArrayList<>(); Student student = null; String text = ""; while (filterReader.hasNext()) { int type = filterReader.next(); if (type == XMLStreamReader.START_ELEMENT) { if ("student".equals(reader.getName().getLocalPart())) { student = new Student(); students.add(student); student.setRollno(Integer.parseInt(reader.getAttributeValue("", "rollno"))); String age = reader.getAttributeValue("http://www.w3.org/TR/html4/school/", "age"); if (StringUtils.isNotBlank(age)) { student.setAge(Integer.parseInt(age)); } } } else if (type == XMLStreamReader.END_ELEMENT) { logger.info(reader.getName().getLocalPart()); if ("firstname".equals(reader.getName().getLocalPart())) { student.setFirstname(text); } else if ("lastname".equals(reader.getName().getLocalPart())) { student.setLastname(text); } else if ("nickname".equals(reader.getName().getLocalPart())) { student.setNickname(text); } else if ("marks".equals(reader.getName().getLocalPart())) { student.setMarks(text); } } else if (type == XMLStreamReader.CHARACTERS) { text = reader.getText(); } } logger.info(students.toString()); } /** * 基于迭代模型的方式解析xml * @throws Exception */ @Test public void parse2() throws Exception { XMLInputFactory2 factory = (XMLInputFactory2)XMLInputFactory.newInstance(); XMLEventReader2 reader = (XMLEventReader2)factory.createXMLEventReader(WoodstoxCase.class.getResourceAsStream("student.xml")); //添加过滤器 XMLEventReader2 filterReader = (XMLEventReader2)factory.createFilteredReader(reader, event -> { //处理开始节点 if (event.isStartElement() || event.isEndElement() || event.isCharacters()) { return true; } return false; }); List<Student> students = new ArrayList<>(); Student student = null; String text = ""; while (filterReader.hasNext()) { XMLEvent event = filterReader.nextEvent(); if (event.isStartElement()) { if ("student".equals(event.asStartElement().getName().getLocalPart())) { student = new Student(); students.add(student); student.setRollno(Integer.parseInt(event.asStartElement().getAttributeByName(new QName("", "rollno")).getValue())); Attribute ageAttribute = event.asStartElement().getAttributeByName(new QName("http://www.w3.org/TR/html4/school/", "age")); if (ageAttribute != null) { student.setAge(Integer.parseInt(ageAttribute.getValue())); } } } else if (event.isEndElement()) { logger.info(event.asEndElement().getName().getLocalPart()); if ("firstname".equals(event.asEndElement().getName().getLocalPart())) { student.setFirstname(text); } else if ("lastname".equals(event.asEndElement().getName().getLocalPart())) { student.setLastname(text); } else if ("nickname".equals(event.asEndElement().getName().getLocalPart())) { student.setNickname(text); } else if ("marks".equals(event.asEndElement().getName().getLocalPart())) { student.setMarks(text); } } else if (event.isCharacters()) { text = event.asCharacters().getData(); } } logger.info(students.toString()); } /** * 生成xml * @throws Exception */ @Test public void toXml() throws Exception { XMLOutputFactory2 factory = (XMLOutputFactory2)XMLOutputFactory2.newInstance(); XMLStreamWriter2 writer = (XMLStreamWriter2)factory.createXMLStreamWriter(System.out); writer.writeStartDocument("UTF-8", "1.0"); writer.writeStartElement("school", "class", "http://www.w3.org/TR/html4/school/"); //第一个学生 writer.writeStartElement("school", "student", "http://www.w3.org/TR/html4/school/"); writer.writeAttribute("rollno", "1"); writer.writeAttribute("school","http://www.w3.org/TR/html4/school/", "age", "10"); writer.writeStartElement("school", "firstname", "http://www.w3.org/TR/html4/school/"); writer.writeCharacters("cxx1"); writer.writeEndElement(); writer.writeStartElement("lastname"); writer.writeCharacters("Bob1"); writer.writeEndElement(); writer.writeStartElement("nickname"); writer.writeCharacters("stars1"); writer.writeEndElement(); writer.writeStartElement("marks"); writer.writeCharacters("85"); writer.writeEndElement(); writer.writeEndElement(); //第二个学生 writer.writeStartElement("student"); writer.writeAttribute("rollno", "2"); writer.writeStartElement("firstname"); writer.writeCharacters("cxx2"); writer.writeEndElement(); writer.writeStartElement("lastname"); writer.writeCharacters("Bob2"); writer.writeEndElement(); writer.writeStartElement("nickname"); writer.writeCharacters("stars2"); writer.writeEndElement(); writer.writeStartElement("marks"); writer.writeCharacters("85"); writer.writeEndElement(); writer.writeEndElement(); //第三个学生 writer.writeStartElement("student"); writer.writeAttribute("rollno", "3"); writer.writeStartElement("firstname"); writer.writeCharacters("cxx3"); writer.writeEndElement(); writer.writeStartElement("lastname"); writer.writeCharacters("Bob3"); writer.writeEndElement(); writer.writeStartElement("nickname"); writer.writeCharacters("stars3"); writer.writeEndElement(); writer.writeStartElement("marks"); writer.writeCharacters("85"); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); } }
Student实体类:
package com.abc.demo.general.xml; /** * 学生 */ public class Student { private int rollno; private int age; private String firstname; private String lastname; private String nickname; private String marks; public Student() {} public Student(int rollno, int age, String firstname, String lastname, String nickname, String marks) { this.rollno = rollno; this.age = age; this.firstname = firstname; this.lastname = lastname; this.nickname = nickname; this.marks = marks; } public int getRollno() { return rollno; } public void setRollno(int rollno) { this.rollno = rollno; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getMarks() { return marks; } public void setMarks(String marks) { this.marks = marks; } @Override public String toString() { return "Student{" + "rollno=" + rollno + ", age=" + age + ", firstname='" + firstname + '\'' + ", lastname='" + lastname + '\'' + ", nickname='" + nickname + '\'' + ", marks='" + marks + '\'' + '}'; } }
来源:https://www.cnblogs.com/wuyongyin/p/14333642.html
最新更新
python爬虫及其可视化
使用python爬取豆瓣电影短评评论内容
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比