VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Java教程 >
  • 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

相关教程