Chinaunix首页 | 论坛 | 博客
  • 博客访问: 530293
  • 博文数量: 135
  • 博客积分: 3568
  • 博客等级: 中校
  • 技术积分: 1942
  • 用 户 组: 普通用户
  • 注册时间: 2006-10-19 17:52
文章分类

全部博文(135)

文章存档

2012年(29)

2011年(41)

2010年(26)

2009年(12)

2008年(9)

2007年(12)

2006年(6)

分类: Java

2010-07-14 22:16:16

貌似现在解决 Java 读XML有很多技术,直接将 JavaBean 和 XML 转换也有很多好的工具。
比如 Java Architecture for XML Binding (JAXB), Xstream, Castor等。
因为先接触Castor了,所以先拿它做个Sample。


输出结果:
Output.txt


----------------------testIntrospectionMode()
log4j:WARN No appenders could be found for logger (org.exolab.castor.mapping.Mapping).
log4j:WARN Please initialize the log4j system properly.

-------Marshall (Bean -> XML)
<?xml version="1.0" encoding="UTF-8"?>
<person>
    <name>son</name>
    <age>25</age>
    <male>true</male>
    <birthday>1985-05-05T05:05:05.005+08:00</birthday>
    <alias>S_A_0</alias>
    <alias>S_A_1</alias>
    <alias>S_A_2</alias>
    <image-data>AQIDBA==</image-data>
    <favors>S_F_0</favors>
    <favors>S_F_1</favors>
    <favors>S_F_2</favors>
    <favors> test
    &lt;&gt;,""_'ABC'&amp;&amp;|| </favors>
    <field>
        <key>SD</key>
        <value>ShanDong</value>
    </field>
    <field>
        <key>HN</key>
        <value>HeNan</value>
    </field>
    <parent>
        <name>mom</name>
        <age>50</age>
        <male>false</male>
        <birthday>1960-06-06T06:06:06.006+08:00</birthday>
        <alias>M_A_0</alias>
        <alias>M_A_1</alias>
        <alias>M_A_2</alias>
        <image-data>ChQeKA==</image-data>
        <favors>M_F_0</favors>
        <favors>M_F_1</favors>
        <favors>M_F_2</favors>
        <field>
            <key>TJ</key>
            <value>TianJin</value>
        </field>
        <field>
            <key>BJ</key>
            <value>BeiJing</value>
        </field>
    </parent>
</person>


-------UnMarshall (XML -> Bean)
name = son
age =25
male =true
birthday =1985/05/05
alias =S_A_0, S_A_1, S_A_2,
imageDate =1, 2, 3, 4,
favors =[S_F_0, S_F_1, S_F_2, test <>,""_'ABC'&&||]
addrs ={SD=ShanDong, HN=HeNan}
nullObject=null

parent
name = mom
age =50
male =false
birthday =1960/06/06
alias =M_A_0, M_A_1, M_A_2,
imageDate =10, 20, 30, 40,
favors =[M_F_0, M_F_1, M_F_2]
addrs ={TJ=TianJin, BJ=BeiJing}
nullObject=null

parent
null



源代码:

文件:TestCastor.rar
大小:3KB
下载:下载

Person.java

package me.test;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class Person {

    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    private boolean male;

    private Date birthday;
    private String[] alias;

    private byte[] imageData;
    private List<String> favors;
    private Map<String, String> addrs;
    private Object nullObject = null;

    private Person parent;
    private Person child;

    public String toString() {
        StringBuilder buf = new StringBuilder();
        buf.append("name\t= " + name);
        buf.append("\nage\t=" + age);
        buf.append("\nmale\t=" + male);
        SimpleDateFormat smf = new SimpleDateFormat("yyyy/MM/dd");
        buf.append("\nbirthday\t=" + smf.format(birthday));
        buf.append("\nalias\t=");
        for (String s : alias) {
            buf.append(s);
            buf.append(", ");
        }
        buf.append("\nimageDate\t=");
        for (byte b : imageData) {
            buf.append(b);
            buf.append(", ");
        }
        buf.append("\nfavors\t=" + favors);
        buf.append("\naddrs\t=" + addrs);
        buf.append("\nnullObject=" + nullObject);
        
        buf.append("\n\nparent\n" + parent);
        
        return buf.toString();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isMale() {
        return male;
    }

    public void setMale(boolean male) {
        this.male = male;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String[] getAlias() {
        return alias;
    }

    public void setAlias(String[] alias) {
        this.alias = alias;
    }

    public byte[] getImageData() {
        return imageData;
    }

    public void setImageData(byte[] imageData) {
        this.imageData = imageData;
    }

    public List<String> getFavors() {
        return favors;
    }

    public void setFavors(List<String> favors) {
        this.favors = favors;
    }

    public Map<String, String> getAddrs() {
        return addrs;
    }

    public void setAddrs(Map<String, String> addrs) {
        this.addrs = addrs;
    }

    public Person getParent() {
        return parent;
    }

    public void setParent(Person parent) {
        this.parent = parent;
    }

    public Person getChild() {
        return child;
    }

    public void setChild(Person child) {
        this.child = child;
    }

    public Object getNullObject() {
        return nullObject;
    }

    public void setNullObject(Object nullObject) {
        this.nullObject = null;
    }

}


Person-mapping.xml

<?xml version="1.0" ?>
<!DOCTYPE databases PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN"
                           "">
<mapping>
  <description>Default Mapping</description>
  <class name="me.test.Person">
    <field name="name" type="java.lang.String"/>
    <field name="age" type="int"/>
    <field name="male" type="boolean"/>
    <field name="birthday" type="java.util.Date"/>
    <field name="alias" type="java.lang.String" collection="array"/>
    <!-- <field name="imageData" type="byte" collection="array"/> -->
    <field name="imageData" type="[B"/>
    <field name="favors" type="java.lang.String" collection="arraylist">
    </field>
    <field name="addrs" type="org.exolab.castor.mapping.MapItem" collection="map">
      <bind-xml name="field" node="element">
        <class name="org.exolab.castor.mapping.MapItem">
          <field name="key" type="java.lang.String">
            <bind-xml name="key" node="element"/>
          </field>
          <field name="value" type="java.lang.String">
            <bind-xml name="value" node="element"/>
          </field>
        </class>
      </bind-xml>
    </field>
    <field name="nullObject" type="java.lang.Object"/>
    <field name="parent" type="me.test.Person"/>
    <field name="child" type="me.test.Person"/>
  </class>
</mapping>


castor.properties

# Example properties indent the output, require validation
# on input and turn debugging on.
#
org.exolab.castor.validation=false
org.exolab.castor.indent=true
org.exolab.castor.debug=true

# True if database configuration should be initalization
# when loading it (default: true).
#
#org.exolab.castor.jdo.DatabaseInitializeAtLoad=true

#
# TransactionManagerFactory implementations
#
org.castor.transactionmanager.Factories=\
  org.castor.transactionmanager.WebSphereTransactionManagerFactory,\
  org.castor.transactionmanager.WebSphere5TransactionManagerFactory,\
  org.castor.transactionmanager.WebSphere51TransactionManagerFactory,\
  org.castor.transactionmanager.LocalTransactionManagerFactory,\
  org.castor.transactionmanager.JNDIENCTransactionManagerFactory,\
  org.castor.transactionmanager.JOTMTransactionManagerFactory

#
# Shell the TransactionManager be initialized at registration or lazily when
# requested for the first time? Defaults to false.
#
org.castor.transactionmanager.InitializeAtRegistration=false


TestCastor.java

package me.test;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

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

// Question: how to marshal/unmarshall List>> ???

public class TestCastor {

    public static void main(String[] args) throws Exception {
        testIntrospectionMode();
    }

    public static void testIntrospectionMode() throws Exception {
        System.out.println("\n----------------------testIntrospectionMode()");
        Person son = new Person();
        Person mom = new Person();

        // -----------------------Person:Son----------------------

        son.setName("son");
        son.setAge(25);
        son.setMale(true);

        Calendar calendar = Calendar.getInstance();
        calendar.set(1985, 4, 5, 5, 5, 5);
        calendar.set(Calendar.MILLISECOND, 5);
        son.setBirthday(calendar.getTime());
        son.setAlias(new String[] { "S_A_0", "S_A_1", "S_A_2" });
        son.setImageData(new byte[] { 1, 2, 3, 4 });
        son.setFavors(Arrays.asList(new String[] { "S_F_0", "S_F_1", "S_F_2",
                " test \n\t<>,\"\"_'ABC'&&|| " }));

        Map<String, String> addrs = new HashMap<String, String>(); // unOrdered

        addrs.put("HN", "HeNan");
        addrs.put("SD", "ShanDong");

        son.setAddrs(addrs);
        son.setParent(mom);

        // -----------------------Person:Mom----------------------

        mom.setName("mom");
        mom.setAge(50);
        mom.setMale(false);
        calendar.set(1960, 5, 6, 6, 6, 6);
        calendar.set(Calendar.MILLISECOND, 6);
        mom.setBirthday(calendar.getTime());
        mom.setAlias(new String[] { "M_A_0", "M_A_1", "M_A_2" });
        mom.setImageData(new byte[] { 10, 20, 30, 40 });
        mom
                .setFavors(Arrays.asList(new String[] { "M_F_0", "M_F_1",
                        "M_F_2" }));
        addrs = new HashMap<String, String>();
        addrs.put("BJ", "BeiJing");
        addrs.put("TJ", "TianJin");
        mom.setAddrs(addrs);
        mom.setChild(son); // NOTICE : Cycle Reference


        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Map<String, String> map = new LinkedHashMap<String, String>(); // ordered

        map.put("AAA", "111");
        map.put("BBB", "222");
        list.add(map);

        // Prepare context

        StringWriter writer = new StringWriter();
        Mapping mapping = new Mapping();
        mapping.loadMapping(Person.class.getResource("Person-mapping.xml"));
        XMLContext context = new XMLContext();
        context.addMapping(mapping);

        // Marshal (Bean -> XML)

        System.out.println("\n-------Marshall (Bean -> XML)");
        Marshaller marshaller = context.createMarshaller();
        marshaller.setWriter(writer);
        marshaller.marshal(son);
        System.out.println(writer);

        // UnMarshal (XML -> Bean)

        System.out.println("\n-------UnMarshall (XML -> Bean)");
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Person newSon = (Person)unmarshaller.unmarshal(new StringReader(writer.toString()));
        System.out.println(newSon.toString());
    }
}


阅读(1054) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~