[XML]castor: java对象与xml间的转换

原文链接:http://hi.baidu.com/jidongxx/blog/item/752cd61b3038fcfdaf51339d.html

说明:交换数据时,可以考虑使用castor,把Java对象的转换成xml 进行远程传递【代替序列化】

     参考中说:castor和xmlbeans这种都是先定义schema,然后根据schema来generate java class,然后调用marshall和unmarshall方法来序列化javabean。这是属于重量级的方法,虽然功能强大,使用却不方便。如果你改了schema,势必要重新generate,这样你就不能在generate的java class上加上自己的方法。导致生成的java class纯粹用于serialize

使用过程:

1. 根据应用逻辑, 编写xml schema文件。示例如下:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://dhgate.com/Test/ProductPromotionAd">

   <xs:element name="ProductPromotionAdResultItem">
        <xs:complexType>
         <xs:sequence>
              <xs:element name="itemcode" type="xs:string"/>
              <xs:element name="hasPromotionAd" type="xs:boolean"/>
          </xs:sequence>
       </xs:complexType>
    </xs:element>
     
   <xs:element name="ProductPromotionAdResults">  
      <xs:complexType>
          <xs:sequence>
             <xs:element ref="ProductPromotionAdResultItem" maxOccurs="unbounded" minOccurs="1"/>       
        </xs:sequence>
      </xs:complexType>
   </xs:element>

</xs:schema>

2.castor 根据xml schema 生成JavaBean;编写类似的脚本如下:
@echo off
REM Change the following line to set your JDK path
set JAVA_HOME=%JAVA_HOME%
set JAVA=%JAVA_HOME%/bin/java
set JAVAC=%JAVA_HOME%/bin/javac

@echo Create the classpath
set CP=.
for %%i in (../../../lib/*.jar) do set CP=%CP%;%%i
set CP=%CP%;../../../build/classes;%JDK_BIN%/lib/tools.jar

@echo.
@echo Using classpath: %CP%

@echo Castor Test Cases
@echo.
@echo Generating classes...

@rem Java 2 style collection types
@rem %JAVA% org.exolab.castor.builder.SourceGeneratorMain -i productPromotionAd.xsd -f -types j2
@rem Java 1.1 collection types
%JAVA% -cp %CP% org.exolab.castor.builder.SourceGeneratorMain -i productPromotionAd.xsd -f

或者利用ant生成,其代码段示例为:

<target name="generateCastorClasses" depends=".">
<java classname="org.exolab.castor.builder.SourceGenerator">
<arg line="-dest '${dir}/source' -i '${dir}/config/Export.xsd' -f -package com.object" />
<classpath>
<fileset dir="${dir}/lib">
<include name="*.jar" />
</fileset>
</classpath>
</java>
</target>

3. 客户服务器端使用JavaBean, 传输时, 服务器端把JavaBean Marshall 成xml, 客户端把xml unmarshall成 JavaBean

测试代码如下:

public class TestCastorXml{
    private static void readTest() {
        try {
           
            ProductPromotionAdResults readXml = ProductPromotionAdResults.unmarshal(new FileReader("e://text.xml"));
            for(int i=0; i<readXml.getProductPromotionAdResultItemCount(); i++) {
                System.out.println(readXml.getProductPromotionAdResultItem(i).getItemcode() + "-->" +
                        readXml.getProductPromotionAdResultItem(i).getHasPromotionAd());
            }
           
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
   
    private static void writeTest() {
        try {
            Writer w = new FileWriter("e://text.xml");
           
            ProductPromotionAdResults resultXml=new ProductPromotionAdResults();
           
            for(int i=0; i<3; i++) {
                ProductPromotionAdResultItem item = new ProductPromotionAdResultItem();
                item.setItemcode(i + "");
                item.setHasPromotionAd(true);
               
                resultXml.addProductPromotionAdResultItem(item);
                System.out.println("write finished");
            }
           
            resultXml.marshal(w);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
   
    public static void main(String[] args) {
        //writeTest();
        readTest();
    }
}

附录:需要的包

castor-1.2-anttasks.jar

castor-1.2-codegen.jar

castor-1.2-ddlgen.jar

castor-1.2-jdo.jar

castor-1.2-xml-schema.jar

castor-1.2-xml.jar

castor-1.2.jar

commons-collections-3.2.jar

commons-lang-2.1.jar

commons-logging-1.1.jar

derby-10.1.2.1.jar

jdbc-se2.0.jar

jta1.0.1.jar

log4j-1.2.8.jar

velocity-dep-1.5.jar

xerces-J_1.4.0.jar

你可能感兴趣的:(java,exception,xml,schema,Class,Types)