-
Java操作XML(9)--Castor使用
Castor是ExoLab Group下面的一个开放源代码的项目,主要实现将java对象和XML绑定的功能,类似JAXB。本文主要介绍Castor基本使用,文中所使用到的软件版本:Java 1.8.0_191、castor-xml 1.4.1。
1、绑定规则
Castor通过配置文件来配置Java对象和XML文件的对应关系,以此根据Java对象生成XML文件或根据XML文件生成Java对象。详细规则说明看参加官网:http://castor.exolab.org/xml-mapping.html。
1.1、<mapping>
<!ELEMENT mapping ( description?, include*, class*, key-generator* )>
配置文件的根节点
1.2、<class>
<!ELEMENT class ( description?, cache-type?, map-to?, field+ )> <!ATTLIST class name ID #REQUIRED extends IDREF #IMPLIED depends IDREF #IMPLIED auto-complete ( true |false ) "false" identity CDATA #IMPLIED access ( read-only | shared | exclusive | db-locked ) "shared" key-generator IDREF #IMPLIED >
定义映射的Java类。
name:类的全路径名称
1.3、<map-to>
<!ELEMENT map-to EMPTY> <!ATTLIST map-to table NMTOKEN #IMPLIED xml NMTOKEN #IMPLIED ns-uri NMTOKEN #IMPLIED ns-prefix NMTOKEN #IMPLIED ldap-dn NMTOKEN #IMPLIED ldap-oc NMTOKEN #IMPLIED>
指定根对象对应的XML节点名称,只用在根对象上。
xml:节点名称
ns-uri:命名空间uri
ns-prefix:命名空间前缀
1.4、<field>
<!ELEMENT field ( description?, sql?, bind-xml?, ldap? )> <!ATTLIST field name NMTOKEN #REQUIRED type NMTOKEN #IMPLIED handler NMTOKEN #IMPLIED required ( true | false ) "false" direct ( true | false ) "false" lazy ( true | false ) "false" transient ( true | false ) "false" get-method NMTOKEN #IMPLIED set-method NMTOKEN #IMPLIED create-method NMTOKEN #IMPLIED collection ( array | vector | hashtable | collection | set | map ) #IMPLIED>
定义Java对象中需要O/X转换的属性。
name:属性名称
type:属性类型
collection:表示父类对象包含多个子类对象
collection可设置的值为:
name | <type> | default implementation |
---|---|---|
array | <type_attribute>[] | <type_attribute>[] |
arraylist | java.util.ArrayList | java.util.Arraylist |
vector | java.util.Vector | java.util.Vector |
hashtable | java.util.Hashtable | java.util.Hashtable |
collection | java.util.Collection | java.util.Arraylist |
set | java.util.Set | java.util.Hashset |
map | java.util.Map | java.util.Hashmap |
1.5、<bind-xml>
<!ELEMENT bind-xml (class?, property*)> <!ATTLIST bind-xml name NMTOKEN #IMPLIED type NMTOKEN #IMPLIED location CDATA #IMPLIED matches NMTOKENS #IMPLIED QName-prefix NMTOKEN #IMPLIED reference ( true | false ) "false" node ( attribute | element | text ) #IMPLIED auto-naming ( deriveByClass | deriveByField ) #IMPLIED transient ( true | false ) "false">
指定Java的属性如何映射到XML文档中。
name:XML节点或属性名称
node:指定name表示的名称为节点、属性或文本
2、Castor使用
2.1、引入依赖
<dependency> <groupId>org.codehaus.castor</groupId> <artifactId>castor-xml</artifactId> <version>1.4.1</version> </dependency>
2.2、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="11"> <school:firstname>cxx1</school:firstname> <lastname>Bob1</lastname> <nickname>stars1</nickname> <marks>85</marks> </school:student> <school:student rollno="2" school:age="12"> <school:firstname>cxx2</school:firstname> <lastname>Bob2</lastname> <nickname>stars2</nickname> <marks>85</marks> </school:student> <school:student rollno="3" school:age="13"> <school:firstname>cxx3</school:firstname> <lastname>Bob3</lastname> <nickname>stars3</nickname> <marks>85</marks> </school:student> </school:grade>
2.3、xml对应的类
2.3.1、班级类
package com.abc.demo.general.xml; import java.util.List; /** * 班级 */ public class Grade { private List<Student> students; public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } @Override public String toString() { return "Grade{" + "students=" + students + '}'; } }
2.3.2、学生类
package com.abc.demo.general.xml; import javax.xml.bind.annotation.*; /** * 学生 */ 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 + '\'' + '}'; } }
2.4、映射规则文件mapping.xml
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN" "http://castor.org/mapping.dtd"> <mapping> <class name="com.abc.demo.general.xml.Grade"> <map-to xml="grade" ns-prefix="school" ns-uri="http://www.w3.org/TR/html4/school/"/> <field name="students" type="com.abc.demo.general.xml.Student" collection="arraylist"> <bind-xml name="student"></bind-xml> </field> </class> <class name="com.abc.demo.general.xml.Student"> <!--<map-to ns-prefix="" ns-uri=""></map-to>--> <field name="rollno"> <bind-xml name="rollno" node="attribute"></bind-xml> </field> <field name="age"> <bind-xml name="school:age" node="attribute" xmlns:school="http://www.w3.org/TR/html4/school/"></bind-xml> </field> <field name="firstname"> <bind-xml name="school:firstname" node="element" xmlns:school="http://www.w3.org/TR/html4/school/"></bind-xml> </field> <field name="lastname"> <bind-xml name="lastname" node="element"></bind-xml> </field> <field name="nickname"> <bind-xml name="nickname" node="element"></bind-xml> </field> <field name="marks"> <bind-xml name="marks" node="element"></bind-xml> </field> </class> </mapping>
2.5、Castor使用例子
该例子演示了使用Castor来处理O/X转换:Java对象转成xml以及xml转成Java对象。
package com.abc.demo.general.xml; import org.exolab.castor.mapping.Mapping; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.Unmarshaller; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; /** * Castor使用 */ public class CastorCase { private static Logger logger = LoggerFactory.getLogger(CastorCase.class); /** * java对象转成xml * @throws Exception */ @Test public void javaToXml() throws Exception { List<Student> students = new ArrayList<>(); Student student1 = new Student(1, 11,"cxx1", "Bob1", "stars1", "85"); Student student2 = new Student(2, 12, "cxx2", "Bob2", "stars2", "85"); Student student3 = new Student(3, 13, "cxx3", "Bob3", "stars3", "85"); students.add(student1); students.add(student2); students.add(student3); Grade grade = new Grade(); grade.setStudents(students); StringWriter sw = new StringWriter(); Marshaller marshaller = new Marshaller(sw); Mapping mapping = new Mapping(); mapping.loadMapping(DomCase.class.getResource("mapping.xml")); marshaller.setMapping(mapping); marshaller.marshal(grade); logger.info(sw.toString()); } /** * xml转成java对象 * @throws Exception */ @Test public void xmlToJava() throws Exception { InputStreamReader reader = new InputStreamReader(CastorCase.class.getResourceAsStream("student2.xml")); Unmarshaller unmarshaller = new Unmarshaller(Grade.class); Mapping mapping = new Mapping(); mapping.loadMapping(DomCase.class.getResource("mapping.xml")); unmarshaller.setMapping(mapping); // Classes classes = (Classes) Unmarshaller.unmarshal(Classes.class, reader); Grade grade = (Grade) unmarshaller.unmarshal(reader); logger.info(grade.toString()); } }
来源:https://www.cnblogs.com/wuyongyin/p/14338604.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() 对比