dom4j-dom-sax解析

2024-08-31 22:58
文章标签 解析 dom sax dom4j

本文主要是介绍dom4j-dom-sax解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://www.example.org/web-app_2_5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.example.org/web-app_2_5 web-app_2_5.xsd"version="2.5"><servlet><servlet-name>MyServlet1</servlet-name><servlet-class>cn.itheima.web.servlet1.MyServlet1</servlet-class></servlet><servlet-mapping><servlet-name>MyServlet1</servlet-name><url-pattern>/myServlet1</url-pattern></servlet-mapping><servlet><servlet-name>MyServlet2</servlet-name><servlet-class>cn.itheima.web.servlet1.MyServlet2</servlet-class></servlet><servlet-mapping><servlet-name>MyServlet2</servlet-name><url-pattern>/myServlet2</url-pattern></servlet-mapping>
</web-app>
利用dom4j进行xml解析
package cn.itheima.xml.dom4j;import java.util.List;import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;public class TestDom4j {@Testpublic void testReadWebXML() {try {// 1.获取解析器SAXReader saxReader = new SAXReader();// 2.获得document文档对象Document doc = saxReader.read("src/cn/itheima/web/servlet1/web.xml");// 3.获取根元素Element rootElement = doc.getRootElement();// System.out.println(rootElement.getName());//获取根元素的名称// System.out.println(rootElement.attributeValue("version"));//获取根元素中的属性值// 4.获取根元素下的子元素List<Element> childElements = rootElement.elements();// 5.遍历子元素for (Element element : childElements) {//6.判断元素名称为servlet的元素if ("servlet".equals(element.getName())) {//7.获取servlet-name元素Element servletName = element.element("servlet-name");//8.获取servlet-class元素Element servletClass = element.element("servlet-class");System.out.println(servletName.getText());System.out.println(servletClass.getText());}}} catch (DocumentException e) {e.printStackTrace();}}}

输出如下:

MyServlet1
cn.itheima.web.servlet1.MyServlet1
MyServlet2
cn.itheima.web.servlet1.MyServlet2
通过解析xml配置文件,利用反射获取对象,然后在执行对象方法
package cn.itheima.web.servlet1;public interface IMyServlet {public void init();public void service();public void destory();
}
package cn.itheima.web.servlet1;public class MyServlet1 implements IMyServlet{@Overridepublic void init() {System.out.println("MyServlet1诞生了……");}@Overridepublic void service() {System.out.println("MyServlet1开始服务了……");}@Overridepublic void destory() {System.out.println("MyServlet1销毁了……");}}
package cn.itheima.web.servlet1;import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;public class TestMyServlet {@Testpublic void testMyServlet(){try {//1.创建解析器对象SAXReader saxReader = new SAXReader();//2.使用解析器加载web.xml文件得到document对象Document document = saxReader.read("src/cn/itheima/web/servlet1/web.xml");//3.获取根元素节点Element rootElement = document.getRootElement();//4.根据元素名称获取子元素节点Element servletElement = rootElement.element("servlet");//5.根据元素名称获取servlet-class的文本节点String servletClass = servletElement.element("servlet-class").getText();//System.out.println(servletClass);//6.通过类全名获取字节码文件Class clazz = Class.forName(servletClass);//7.创建实例对象MyServlet1 my = (MyServlet1) clazz.newInstance();//8.调用实例对象里面的方法my.init();my.service();my.destory();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}

输出如下:

MyServlet1诞生了……
MyServlet1开始服务了……
MyServlet1销毁了……
dom解析

配置文件放在项目根目录下,跟src平行

<?xml version="1.0" encoding="UTF-8"?>
<bookstore><book category="children"><title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book><book category="cooking"><title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book><book category="web"><title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</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></bookstore>
package cn.itheima.xml.dom4j;import java.io.File;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;public class DomTest1
{public static void main(String[] args) throws Exception{// step 1:获得DOM解析器工厂// 工厂的作用是创建具体的解析器DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();// step 2:获得具体的dom解析器DocumentBuilder db = dbf.newDocumentBuilder();// step 3:解析一个xml文档,获得Document对象(根节点)// 此文档放在项目目录下即可Document document = db.parse(new File("NewFile.xml"));// 根据标签名访问节点NodeList list = document.getElementsByTagName("book");System.out.println("list length: " + list.getLength());// 遍历每一个节点for (int i = 0; i < list.getLength(); ++i){System.out.println("----------------------");// 获得元素,将节点强制转换为元素Element element = (Element) list.item(i);// 此时element就是一个具体的元素// 获取子元素:子元素title只有一个节点,之后通过getNodeValue方法获取节点的值String content0 = element.getElementsByTagName("title").item(0).getNodeValue();System.out.println(content0);// 此处打印出为null// 因为节点getNodeValue的值永远为null// 解决方法:加上getFirstChild()   public Node item(int index);String content = element.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();System.out.println("title: " + content);// 此处打印出书名// 后面类似处理即可:content = element.getElementsByTagName("author").item(0).getFirstChild().getNodeValue();System.out.println("author: " + content);content = element.getElementsByTagName("year").item(0).getFirstChild().getNodeValue();System.out.println("year: " + content);content = element.getElementsByTagName("price").item(0).getFirstChild().getNodeValue();System.out.println("price: " + content);}}}
list length: 4
----------------------
null
title: Harry Potter
author: J K. Rowling
year: 2005
price: 29.99
----------------------
null
title: Everyday Italian
author: Giada De Laurentiis
year: 2005
price: 30.00
----------------------
null
title: Learning XML
author: Erik T. Ray
year: 2003
price: 39.95
----------------------
null
title: XQuery Kick Start
author: James McGovern
year: 2003
price: 49.99
sax解析

配置文件在src目录下,不是平级

<?xml version="1.0" encoding="UTF-8"?>  <root>  <student id="1" group="1">  <name>张三</name>  <sex></sex>  <age>18</age>  <email>zhangsan@163.com</email>  <birthday>1987-06-08</birthday>  <memo>好学生</memo>  </student>  <student id="2" group="2">  <name>李四</name>  <sex></sex>  <age>18</age>  <email>lisi@163.com</email>  <birthday>1987-06-08</birthday>  <memo>好学生</memo>  </student>  <student id="3" group="3">  <name>小王</name>  <sex></sex>  <age>18</age>  <email>xiaowang@163.com</email>  <birthday>1987-06-08</birthday>  <memo>好学生</memo>  </student>  <student id="4" group="4">  <name>小张</name>  <sex></sex>  <age>18</age>  <email>xiaozhang@163.com</email>  <birthday>1987-06-08</birthday>  <memo>好学生</memo>  </student>  <student id="5" group="5">  <name>小明</name>  <sex></sex>  <age>18</age>  <email>xiaoming@163.com</email>  <birthday>1987-06-08</birthday>  <memo>好学生</memo>  </student>  </root>
package cn.itheima.xml.dom4j;
public class Student {  private int id;  private int group;  private String name;  private String sex;  private int age;  private String email;  private String memo;  private String birthday;  public int getId() {  return id;  }  public void setId(int id) {  this.id = id;  }  public int getGroup() {  return group;  }  public void setGroup(int group) {  this.group = group;  }  public String getName() {  return name;  }  public void setName(String name) {  this.name = name;  }  public String getSex() {  return sex;  }  public void setSex(String sex) {  this.sex = sex;  }  public int getAge() {  return age;  }  public void setAge(int age) {  this.age = age;  }  public String getEmail() {  return email;  }  public void setEmail(String email) {  this.email = email;  }  public String getMemo() {  return memo;  }  public void setMemo(String memo) {  this.memo = memo;  }  public String getBirthday() {  return birthday;  }  public void setBirthday(String birthday) {  this.birthday = birthday;  }  }  
package cn.itheima.xml.dom4j;
import java.util.ArrayList;  
import java.util.List;  import org.xml.sax.Attributes;  
import org.xml.sax.SAXException;  
import org.xml.sax.helpers.DefaultHandler;  /**  * 功能描述:采用sax方式解析XML<br>  *   * @author sxyx2008  *  */  
public class SaxParseXml extends DefaultHandler{  //存放遍历集合  private List<Student> list;  //构建Student对象  private Student student;  //用来存放每次遍历后的元素名称(节点名称)  private String tagName;  public List<Student> getList() {  return list;  }  public void setList(List<Student> list) {  this.list = list;  }  public Student getStudent() {  return student;  }  public void setStudent(Student student) {  this.student = student;  }  public String getTagName() {  return tagName;  }  public void setTagName(String tagName) {  this.tagName = tagName;  }  //只调用一次  初始化list集合    @Override  public void startDocument() throws SAXException {  list=new ArrayList<Student>();  }  //调用多次    开始解析  @Override  public void startElement(String uri, String localName, String qName,  Attributes attributes) throws SAXException {  if(qName.equals("student")){  student=new Student();  //获取student节点上的id属性值  student.setId(Integer.parseInt(attributes.getValue(0)));  //获取student节点上的group属性值  student.setGroup(Integer.parseInt(attributes.getValue(1)));  }  this.tagName=qName;  }  //调用多次    @Override  public void endElement(String uri, String localName, String qName)  throws SAXException {  if(qName.equals("student")){  this.list.add(this.student);  }  this.tagName=null;  }  //只调用一次  @Override  public void endDocument() throws SAXException {  }  //调用多次  @Override  public void characters(char[] ch, int start, int length)  throws SAXException {  if(this.tagName!=null){  String date=new String(ch,start,length);  if(this.tagName.equals("name")){  this.student.setName(date);  }  else if(this.tagName.equals("sex")){  this.student.setSex(date);  }  else if(this.tagName.equals("age")){  this.student.setAge(Integer.parseInt(date));  }  else if(this.tagName.equals("email")){  this.student.setEmail(date);  }  else if(this.tagName.equals("birthday")){  this.student.setBirthday(date);  }  else if(this.tagName.equals("memo")){  this.student.setMemo(date);  }  }  }  
}  
package cn.itheima.xml.dom4j;
import javax.xml.parsers.SAXParser;  
import javax.xml.parsers.ParserConfigurationException;  
import javax.xml.parsers.SAXParserFactory;  import org.xml.sax.SAXException;  import java.io.IOException;  
import java.io.InputStream;  
import java.util.List;  public class Test {  public static void main(String[] args) {  SAXParser parser = null;  try {  //构建SAXParser  parser = SAXParserFactory.newInstance().newSAXParser();  //实例化  DefaultHandler对象  SaxParseXml parseXml=new SaxParseXml();  //加载资源文件 转化为一个输入流  InputStream stream=SaxParseXml.class.getClassLoader().getResourceAsStream("student.xml");  //调用parse()方法  parser.parse(stream, parseXml);  //遍历结果  List<Student> list=parseXml.getList();  for(Student student:list){  System.out.println("id:"+student.getId()+"\tgroup:"+student.getGroup()+"\tname:"+student.getName()+"\tsex:"+student.getSex()+"\tage:"+student.getAge()+"\temail:"+student.getEmail()+"\tbirthday:"+student.getBirthday()+"\tmemo:"+student.getMemo());  }  } catch (ParserConfigurationException e) {  e.printStackTrace();  } catch (SAXException e) {  e.printStackTrace();  } catch (IOException e) {  e.printStackTrace();  }  }  }  
id:1    group:1 name:张三 sex:男   age:18  email:zhangsan@163.com  birthday:1987-06-08 memo:好学生
id:2    group:2 name:李四 sex:女   age:18  email:lisi@163.com  birthday:1987-06-08 memo:好学生
id:3    group:3 name:小王 sex:男   age:18  email:xiaowang@163.com  birthday:1987-06-08 memo:好学生
id:4    group:4 name:小张 sex:男   age:18  email:xiaozhang@163.com birthday:1987-06-08 memo:好学生
id:5    group:5 name:小明 sex:男   age:18  email:xiaoming@163.com  birthday:1987-06-08 memo:好学生

这篇关于dom4j-dom-sax解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1125236

相关文章

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

CSS place-items: center解析与用法详解

《CSSplace-items:center解析与用法详解》place-items:center;是一个强大的CSS简写属性,用于同时控制网格(Grid)和弹性盒(Flexbox)... place-items: center; 是一个强大的 css 简写属性,用于同时控制 网格(Grid) 和 弹性盒(F

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

Python包管理工具核心指令uvx举例详细解析

《Python包管理工具核心指令uvx举例详细解析》:本文主要介绍Python包管理工具核心指令uvx的相关资料,uvx是uv工具链中用于临时运行Python命令行工具的高效执行器,依托Rust实... 目录一、uvx 的定位与核心功能二、uvx 的典型应用场景三、uvx 与传统工具对比四、uvx 的技术实

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

Redis过期删除机制与内存淘汰策略的解析指南

《Redis过期删除机制与内存淘汰策略的解析指南》在使用Redis构建缓存系统时,很多开发者只设置了EXPIRE但却忽略了背后Redis的过期删除机制与内存淘汰策略,下面小编就来和大家详细介绍一下... 目录1、简述2、Redis http://www.chinasem.cn的过期删除策略(Key Expir

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解