1.java中解析 的几种方式
1.1 JDK原生dom形式 原理:一次性把 读入内存,在内存中构建成树形结构。优点:对节点操作方便,缺点:需要大量的内存空间,浪费资源
1.2 SAX形式 原理:基于事件形式,当解析器发现元素开始、元素结束、文本、文档的开始或结束等时,发送事件,程序员编写响应这些事件的代码,保存数据。优点:相对于dom形式更快捷,占用资源少。缺点:没有持久话。事件过后,若没保存数据,那么数据就丢了。
1.3 DOM4J 它是一个开源的框架,具有性能优异、功能强大和极端易用使用的特点。
1.4 JAXB(Java Architecture for Binding) 是一个业界的标准,是一项可以根据 Schema产生Java类的技术。
2.JAXB的几个核心对象
2.1 JAXBContext Jaxb的上下文,通过这个对象我们能拿到另外两个核心对象Unmarshaller(用于解析 )和Marshaller(生成 )
2.2 JAXBContext通常使用它的静态方法newInstance(Class className)来获得对象
2.3 Unmarshaller用于解析 通过JAXBContext的createUnmarshaller方法获得到
2.4 Marshaller用于生成 通过JAXBContext的createMarshaller方法获得到
3.示例代码
3.1 实体类Bean与Property
1 package org.lyrk.accp8.s2.chapter. ; 2 3 import javax. .bind.annotation.*; 4 5 /** 6 * Created by niechen on 17/5/9. 7 */ 8 @ RootElement 9 @ AccessorType( AccessType.FIELD)10 public class Bean {11 12 @ Element13 private Property property;14 15 public Property getProperty() {16 return property;17 }18 19 public void setProperty(Property property) {20 this.property = property;21 }22 }23 24 @ AccessorType(value = AccessType.FIELD)25 class Property {26 @ Attribute(name = "id")27 private String id;28 29 @ Attribute(name = "value")30 private String value;31 32 public String getId() {33 return id;34 }35 36 public void setId(String id) {37 this.id = id;38 }39 40 public String getValue() {41 return value;42 }43 44 public void setValue(String value) {45 this.value = value;46 }47 }
3.2 主函数类
1 package org.lyrk.accp8.s2.chapter. ; 2 3 import javax. .bind.JAXBContext; 4 import javax. .bind.JAXBException; 5 import javax. .bind.Unmarshaller; 6 import java.io.InputStream; 7 8 /** 9 * Created by niechen on 17/5/9.10 */11 public class Test {12 13 public static void main(String[] args) {14 try {15 JAXBContext jaxbContext = JAXBContext.newInstance(Bean.class);//创建JAXBContext对象,注意一定要传@ RootElement的所标记的类的类型16 Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();//拿到 解析对象17 InputStream inputStream = Bean.class.getClassLoader().getResourceAsStream("bean. ");//在classpath下读取 的文件流18 Bean bean = (Bean) unmarshaller.unmarshal(inputStream);//将 转换成实体对象19 System.out.println(bean.getProperty().getId());//输出ID属性20 System.out.println(bean.getProperty().getValue());//输出value属性21 } catch (JAXBException e) {22 e.printStackTrace();23 }24 }25 }
3.3 文件内容
1 <? version="1.0" encoding="UTF-8"?>2 <bean>3 <property id="name" value="10" />4 </bean>
继续阅读与本文标签相同的文章
上一篇 :
聊区块链开发公司 引领生产关系的变革空间
下一篇 :
使用JAXB解析xml文件(二)
-
浅谈MySQL中优化sql语句查询常用的30种方法
2026-06-02栏目: 教程
-
lombok安装与简易教程(一)
2026-06-02栏目: 教程
-
CentOS 7 安装MySQL 5.6遇到问题及解决方案
2026-06-02栏目: 教程
-
centos7安装nginx必要环境
2026-06-02栏目: 教程
-
使用jquery.qrcode.js生成二维码
2026-06-02栏目: 教程
