castor学习笔记

castor是一个可以把java对象和XML进行相互转换的工具包。另外把 Java 对象绑定到 SQL 数据库。在这里,我只说一下java对象和XML的转换。
官方网站:http://www.castor.org/download.html 下载Castor
Castor 几乎是 JAXB 的替代品.Castor 提取出 XML 文档中的数据,并使用自己的 Java 类处理数据。用数据绑定术语来说,这称为解组(unmarshalling)。反向的过程称为编组(marshalling):您应该能够把 Java 类的成员变量中存储的数据转换为 XML 文档.
使用Castor XML
一、 简介
Castor XML是一种XML数据绑定框架。
XML的另外两种主要API:DOM和SAX(Document Object Model和Simple API for XML),主要是从结构的角度去处理XML文件,而Castor XML是以对象的模式去处理XML文档中的数据
大多数情况下,转换框架通过ClassDescriptor和FieldDescriptor来描述转换时所需要的信息。

二、 转换框架
转换框架中最主要的两个类是:org.exolab.castor.xml.Marshaller和org.exolab.castor.xml.Unmarshaller

marshal: Marshaller.marshal(obj,writer);
unmarshal: Unmarshaller.unmarshal(Person.class,reader);

上面的这种转换方式,只适合于按照默认方式进行转化,如果要使用映射文件,需要采用以下方式。
marshal:
Mapping mapping = new Mapping();
mapping.loadMapping(“mapping.xml”);
Marshaller marshaller = new Marshaller(writer);
marshaller.setMapping(mapping);
marshaller.marshal(obj);
Marshaller的5个marshal方法中,只有marshal(Object obj)这个方法不是静态的,其他的四个都是静态的marshal(obj,writer), marshal(obj,handler), marshal(obj,node)

unmarshal:
Mapping mapping = new Mapping();
mapping .loadMapping(“mapping.xml”);
Unmarshaller unm = new Unmarshaller(“Person.class”);//使用Person.class作为构造Unmarshaller的参数
unm.setMapping(mapping);
Person person = (Person)unm.unmarshal(reader);
Unmarshaller中,object可以从reader中转换而来,也可以从source、node转换而来,静态方法均是两个参数,非静态方法都是一个来源作为参数。

三、 使用存在的Class和对象
Castor几乎可以将任何对象和XML进行转换。当指定class的描述文件不存在时,转换框架使用默认的reflection机制来获得对象的信息。

转化对象存在的主要约束是:
这些class必须有一个public而且default的构造函数;必须有adequate get/set方法。

四、 类描述符(ClassDescriptor)
org.exolab.castor.xml.XMLClassDescriptor
类描述符提供转换时所需的必要信息。ClassDescriptor不仅可以用于Castor XML,还可以用于Castor JDO

类描述符包括一组字段描述符(FieldDescriptor)

类描述符通常情况下有四种创建方式,两种在编译时(效率较高),两种在运行时(较为方便)
编译时描述符:
1. 让需要被describe的类实现org.exolab.castor.xml.XMLClassDescriptor接口
2. 使用Source Code Generator创建合适的descriptor
运行时描述符:
3. 默认,使用Castor的introspect机制
4. 提供mapping文件,或者默认和配置文件并用

使用”default introspection”机制必须为每一个要转换的field配备对应的get/set方法;
如果没有get/set方法,但是是public的field,也可以以direct field access的方式被转换;
但是如果一个类中为有的成员定义了get/set方法,即使其他成员是public的,也不会被转换;
自动内省机制是自动触发的。可以通过castor.properties文件控制自动转换的特性,比如改变名称转换、基本型别是转换为attribute还是element等。

Mapping文件也可以用来描述要被转换的类。mapping的装载发生在marshal和unmarshal之前(org.exolab.castor.mapping.Mapping)

例子一:
编组(marshalling)
类CD :
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class CD implements Serializable {

    private String name;
    private String artist;
    private List tracks;
   
    public CD() {
        super();
    }
   
    public CD(String name, String artist) {
        super();
        this.name = name;
        this.artist = artist;
    }

    /**
     * @return the artist
     */
    public String getArtist() {
        return artist;
    }
    /**
     * @param artist the artist to set
     */
    public void setArtist(String artist) {
        this.artist = artist;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return the tracks
     */
    public List getTracks() {
        return tracks;
    }
    /**
     * @param tracks the tracks to set
     */
    public void setTracks(List tracks) {
        this.tracks = tracks;
    }
   
    public void addTracks(String trackName) {
        if(tracks == null) {
            tracks = new ArrayList();
        }
        tracks.add(trackName);
    }
   
}
二:测试类MarshallerTest
import java.io.FileWriter;
import org.exolab.castor.xml.Marshaller;

import cn.wikeup.com.bean.CD;

public class MarshallerTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        CD sessions = new CD("Sessions for Robert J","Eric Clapton");
        sessions.addTracks("Litte Queen of Spades");
        sessions.addTracks("Terraplane Blues");
       
        try {
            FileWriter writer = new FileWriter("cds.xml");
            Marshaller.marshal(sessions, writer);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.err.println(e.getMessage());
            e.printStackTrace(System.err);
        }
    }

}
三:结果cds.xml

  <?xml version="1.0" encoding="UTF-8" ?>
- <CD>
  <artist>Eric Clapton</artist>
  <tracks>Litte Queen of Spades</tracks>
  <tracks>Terraplane Blues</tracks>
  <name>Sessions for Robert J</name>
  </CD>
解组(unmarshalling)
一:测试类

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;

import org.exolab.castor.xml.Unmarshaller;

import cn.wikeup.com.bean.CD;

public class UnmarshalTest {

    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("cds.xml") ;
            CD cd = (CD) Unmarshaller.unmarshal(CD.class, reader);
            System.out.println("CD title:" + cd.getName());
            System.out.println("CD artist:" + cd.getArtist());
            List tracks = cd.getTracks();
            if(tracks == null ) {
                System.out.println("NO tracks.");
            } else {
                for(Object track :tracks) {
                    System.out.println("Track:" + track.toString());
                }
            }
           
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.err.print(e.getMessage());
            e.printStackTrace(System.err);
        }
    }
   
}
二结果:
CD title:Sessions for Robert J
CD artist:Eric Clapton
Track:Litte Queen of Spades
Track:Terraplane Blues


例子二:
类Book
package cn.wikeup.com.bean;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Book {

    private String isbn;
    private String title;
    private List<Author> authors;
   
    public Book() {
    }

    //    private String authorName;
//    private List authorNames;
/*    public Book(String isbn, String title, List authorNames) {
        this.isbn = isbn;
        this.title = title;
        this.authorNames = authorNames;
    }
   
    public Book(String isbn, String title, String authorName) {
        this.isbn = isbn;
        this.title = title;
        this.authorNames = new LinkedList();
        this.authorNames.add(authorName);
    }
   
    public void addAuthorName(String authorName) {
        authorNames.add(authorName);
    }
   
   
    public List getAuthorNames() {
        return authorNames;
    }

   
    public void setAuthorNames(List authorNames) {
        this.authorNames = authorNames;
    }
*/
    public Book(String isbn, String title, List<Author> authors) {
        this.isbn = isbn;
        this.title = title;
        this.authors = authors;
    }
   
    public Book(String isbn, String title, Author author) {
        this.isbn = isbn;
        this.title = title;
        this.authors = new ArrayList<Author>();
        this.authors.add(author);
    }
   
    public void addAuthor(Author author) {
        this.authors.add(author);
    }
   
    /**
     * @return the authors
     */
    public List<Author> getAuthors() {
        return authors;
    }

    /**
     * @param authors the authors to set
     */
    public void setAuthors(List<Author> authors) {
        this.authors = authors;
    }

    /**
     * @return the isbn
     */
    public String getIsbn() {
        return isbn;
    }
    /**
     * @param isbn the isbn to set
     */
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
    /**
     * @return the title
     */
    public String getTitle() {
        return title;
    }
    /**
     * @param title the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }
   
   
}

类Author
package cn.wikeup.com.bean;

public class Author {

    private String firstName, lastName;
//    private int totalSales;
   
   
    public Author() {
    }

    public Author(String firstName, String lastName) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @param lastName the lastName to set
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * @param totalSales the totalSales to set
     */
//    public void setTotalSales(int totalSales) {
//        this.totalSales = totalSales;
//    }
//   
//    public void addToSales(int additionalSales) {
//        this.totalSales += additionalSales;
//    }
//   
//    public int getTotalSales() {
//        return this.totalSales;
//    }
}
映射xml
book-mapping.xml
<?xml version="1.0"?>
<!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN"
          "http://castor.org/mapping.dtd">

<mapping>
  <class name="cn.wikeup.com.bean.Book">
    <map-to xml="book" />

    <field name="Title" type="java.lang.String">
      <bind-xml name="title" node="element" location="book-info" />
    </field>
    <field name="Isbn" type="java.lang.String">
      <bind-xml name="isbn" node="element" location="book-info" />
    </field>

    <field name="Authors" type="cn.wikeup.com.bean.Author" collection="arraylist">
      <bind-xml name="author" />
    </field>
  </class>

  <class name="cn.wikeup.com.bean.Author">
    <field name="FirstName" type="java.lang.String">
      <bind-xml name="first" node="attribute" location="name" />
    </field>

    <field name="LastName" type="java.lang.String">
      <bind-xml name="last" node="attribute" location="name" />
    </field>
  </class>
</mapping>


编组(marshalling)
package cn.wikeup.com.castor;

import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.xml.Marshaller;

import cn.wikeup.com.bean.Author;
import cn.wikeup.com.bean.Book;

public class BookMapMarshaller {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Mapping mapping = new Mapping();
       
        try {
            List<Author> authors = new ArrayList<Author>();
            Book book = new Book();
            authors.add(new Author("yytian", "tian"));
            authors.add(new Author("yytian1", "tian1"));
            book.setAuthors(authors);
            book.setIsbn("11111111111111111");
            book.setTitle("thing in java");
            mapping.loadMapping("book-mapping.xml");
            FileWriter writer = new FileWriter("book7.xml");
            Marshaller marshaller = new Marshaller(writer);
            marshaller.setMapping(mapping);
            marshaller.marshal(book);
            System.out.println("Book ISBN: " + book.getIsbn());
            System.out.println("Book Title: " + book.getTitle());
            authors = book.getAuthors();
            for (Iterator i = authors.iterator(); i.hasNext(); ) {
            Author author = (Author)i.next();
            System.out.println("Author: " + author.getFirstName() + " " +
            author.getLastName());
            }
            System.out.println();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.err.println(e.getMessage());
            e.printStackTrace(System.err);
        }
       
    }
}
结果:book7.xml

<?xml version="1.0" encoding="UTF-8" ?>
- <book>
- <book-info>
  <title>thing in java</title>
  <isbn>11111111111111111</isbn>
  </book-info>
- <author>
  <name first="yytian" last="tian" />
  </author>
- <author>
  <name first="yytian1" last="tian1" />
  </author>
  </book>

解组(unmarshalling)
package cn.wikeup.com.castor;

import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.Unmarshaller;

import cn.wikeup.com.bean.Author;
import cn.wikeup.com.bean.Book;

public class BookMapUnmarshaller {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Mapping mapping = new Mapping();
        try {
           
           
            mapping.loadMapping("book-mapping.xml");
            FileReader reader = new FileReader("book7.xml");
            Unmarshaller unmarshaller = new Unmarshaller(Book.class);
            unmarshaller.setMapping(mapping);
            Book book = (Book) unmarshaller.unmarshal(reader);
            List<Author> authors = book.getAuthors();
            for(Author author:authors) {
                System.out.println("Author: " + author.getFirstName() + " " +
                         author.getLastName());
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.err.println(e.getMessage());
            e.printStackTrace(System.err);
        }
    }

}
结果:

Author: yytian tian
Author: yytian1 tian1

注意点:
1.这些class必须有一个public而且default的构造函数;必须有get/set方法。
2.Java采用用驼峰式(camel-case)命名法比如 de>firstNamede>,XML的风格为(比如 de>first-namede>)映射为 Java 风格的名称(比如 de>firstNamede>)
3.mapping文件中
<field name="Title" type="java.lang.String">                     <bind-xml name="title" node="element" />                    </field>Castor 通过调用 de>set[PropertyName]()de> 来使用这个属性名。例如setTitle中的Title【<field name="Title】,对应于xml中的title【<bind-xml name="title"】参考资料:
1、实现 Castor 数据绑定,第 1 部分: 安装和设置 castor
http://www.ibm.com/developerworks/cn/xml/x-xjavacastor1/
2、实现 Castor 数据绑定,第 2 部分: 编组和解组 XML

http://www.ibm.com/developerworks/cn/xml/x-xjavacastor2/

3、实现 Castor 数据绑定,第 3 部分: 模式之间的映射
http://www.ibm.com/developerworks/cn/xml/x-xjavacastor3/

4、实现 Castor 数据绑定,第 4 部分: 把 Java 对象绑定到 SQL 数据库
http://www.ibm.com/developerworks/cn/xml/x-xjavacastor4/index.html

你可能感兴趣的:(数据结构,xml,bean,框架,IBM)