Castor简单应用

 

       进来的项目中涉及到了JAVA对象到XML格式数据转换问题,经过查找发现Castor是个好东西,于是便简单用了一下!在此我所要说的东西于我的项目关系不大,只是想说一下Castor关于JAVA对象到XML格式数据转换问题的简单应用。     

 CastorExoLab Group下面的一个开放源代码的项目,它主要目标是提供Java对象与XML 的绑定, JavaSQL的持久化等。在此只对Java对象与XML 的绑定作一个简单的应用!以说明其应用方法!

<o:p> </o:p>

一、具体应用<o:p></o:p>

<o:p> </o:p>

1.No Mapping 应用<o:p></o:p>

<o:p> </o:p>

测试bean TestBean.java<o:p></o:p>

package org.ndot;<o:p></o:p>

public class TestBean {<o:p></o:p>

   private String user;<o:p></o:p>

   private String text;<o:p></o:p>

   private int num;<o:p></o:p>

   public int getNum() {<o:p></o:p>

       return num;<o:p></o:p>

   }<o:p></o:p>

   public void setNum(int num) {<o:p></o:p>

       this.num = num;<o:p></o:p>

   }<o:p></o:p>

   public String getText() {<o:p></o:p>

       return text;<o:p></o:p>

   }<o:p></o:p>

   public void setText(String text) {<o:p></o:p>

       this.text = text;<o:p></o:p>

   }<o:p></o:p>

   public String getUser() {<o:p></o:p>

       return user;<o:p></o:p>

   }<o:p></o:p>

   public void setUser(String user) {<o:p></o:p>

       this.user = user;<o:p></o:p>

   }<o:p></o:p>

   public TestBean() {}<o:p></o:p>

}<o:p></o:p>

<o:p> </o:p>

   测试类:MainTest.java<o:p></o:p>

package org.ndot;<o:p></o:p>

import java.io.File;<o:p></o:p>

import java.io.FileReader;<o:p></o:p>

import java.io.FileWriter;<o:p></o:p>

import org.exolab.castor.xml.Marshaller;<o:p></o:p>

import org.exolab.castor.xml.Unmarshaller;<o:p></o:p>

public class MainTest {<o:p></o:p>

  public static void main(String[] args) {  <o:p></o:p>

     TestBean bean = new TestBean();<o:p></o:p>

     bean.setUser("User");<o:p></o:p>

     bean.setText("Test");<o:p></o:p>

     try {<o:p></o:p>

         File file = new File("test.xml");<o:p></o:p>

         if (!file.exists()) {<o:p></o:p>

            file.createNewFile();<o:p></o:p>

         }<o:p></o:p>

         FileWriter writer = new FileWriter(file);<o:p></o:p>

         Marshaller.marshal(bean, writer);<o:p></o:p>

         FileReader reader = new FileReader(file);<o:p></o:p>

     TestBean read = (TestBean) Unmarshaller.<o:p></o:p>

unmarshal(TestBean.class, reader);<o:p></o:p>

         System.out.println(read.getUser()+" : "+read.getText());<o:p></o:p>

     } catch (Exception e) {<o:p></o:p>

         e.printStackTrace(System.err);<o:p></o:p>

     }<o:p></o:p>

  }<o:p></o:p>

}<o:p></o:p>

控制台输出:User : Test<o:p></o:p>

生成test.xml文件:<o:p></o:p>

<?xml version="1.0" encoding="UTF-8"?><o:p></o:p>

<test-bean num="0"><o:p></o:p>

  <user>User</user><o:p></o:p>

  <text>Test</text><o:p></o:p>

</test-bean><o:p></o:p>

<o:p> </o:p>

注意:当bean属性是基本数据类型是作为跟元素的属性对待。而当bean属性是对象类型时按跟元素的子元素对待。<o:p></o:p>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值