您的位置:首页 > 其它

Castor的使用

2016-04-25 15:07 267 查看
因为项目中使用了Castor(xml和对象间的转换),所以自己在网上找了一些资料练习了一下,现在把代码贴出来,留着以后看看!



这是用到的jar包,有一些是没用的!这都是在网上看的

一、(没有配置文件)

public class DefaultCastor
{
//返回此抽象路径的绝对路径字符串
public static final String xmlPath=new File("").getAbsolutePath()+"\\src\\CastorTest\\";

@org.junit.Test
public void Test(){
//        DefaultCastor test=new DefaultCastor();
try
{
beanToxml();
xmlTobean();
} catch (MarshalException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ValidationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 缺省用法没有配置文件
* 编组(marshalling)
* @throws IOException
* @throws ValidationException
* @throws MarshalException
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void beanToxml() throws IOException, MarshalException, ValidationException{
System.out.println(xmlPath+"路径------");
List friend=new ArrayList();
friend.add("zhangsan");
friend.add("lisi");
Map score=new HashMap();
score.put("1", "za");
score.put("2", "na");
String[] hobby={"a","b"};
UserBean user=new UserBean();
user.setName("fenghao");
user.setAge("24");
user.setFriends(friend);
user.setHobby(hobby);
user.setScore(score);
File file=new File(xmlPath+"test.xml");
Writer writer=new FileWriter(file);
Marshaller shaller=new Marshaller(writer);
shaller.setEncoding("utf-8");
shaller.marshal(user);
writer.flush();
writer.close();
}
/**
* xml转成Bean
* 解组
* @throws FileNotFoundException
* @throws ValidationException
* @throws MarshalException
*/
public static void xmlTobean() throws FileNotFoundException, MarshalException, ValidationException{
File file=new File(xmlPath+"test.xml");
System.out.println(file.getAbsolutePath()+"文件路径");
Reader read=new FileReader(file);
//        InputStream in=new FileInputStream(file);
UserBean user=(UserBean)Unmarshaller.unmarshal(UserBean.class, read);
System.out.println("--------------/n");
System.out.println(user.getName()+"-------name/n"+user.getScore().get("1"));
System.out.println("---------------");
try
{
read.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}


二、

这是实体类

package CastorTest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserBean
{
private String name;
private String age;
private String[] hobby;
private Map score;
private List<String> friends;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAge()
{
return age;
}
public void setAge(String age)
{
this.age = age;
}
public String[] getHobby()
{
return hobby;
}
public void setHobby(String[] hobby)
{
this.hobby = hobby;
}
public Map getScore()
{
return score;
}
public void setScore(Map score)
{
this.score = score;
}
public List<String> getFriends()
{
return friends;
}
public void setFriends(List<String> friends)
{
this.friends = friends;
}
public UserBean(String name, String age, String[] hobby, Map score,
List<String> friends)
{
super();
this.name = name;
this.age = age;
this.hobby = hobby;
this.score = score;
this.friends = new ArrayList<String>();
}
public UserBean()
{
super();
// TODO Auto-generated constructor stub
}

}


package CastorTest;
//这是工具类
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FileUtil
{
public static String  readFile(String filePath) throws IOException{
File file=new File(filePath);
BufferedReader read=new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8"));
StringBuffer str=new StringBuffer((int)file.length()+300);//细节性优化方案
String line=null;
while((line=read.readLine())!=null){
str.append(line);
}
read.close();
return str.toString();
}
public static String readFile1(String filePath) throws IOException{
File file=new File(filePath);
InputStream in=null;
in=new FileInputStream(file);
byte b[]=new byte[(int)file.length()];//细节性优化方案
int len=in.read(b);
in.close();
String str=new String(b,0,len);
return str;
}
}


这是映射文件(描述xml和Bean的关系)

<?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="CastorTest.UserBean" auto-complete="true">
<map-to xml="dataset"/>
<field name="name" type="java.lang.String">
<bind-xml name="name" node="element"/>
</field>
<field name="age" type="java.lang.String">
<bind-xml name="age" node="element"/>
</field>
<field name="hobby" type="java.lang.String" collection="array">
<bind-xml name="hobby" node="element"/>
</field>
<field name="score" collection="map">
<class name="org.exolab.castor.mapping.MapItem">
<field name="key" type="java.lang.String">
<bind-xml name="key" node="attribute"/>
</field>
<field name="value" type="java.lang.String">
<bind-xml name="value" node="text"/>
</field>
</class>
</field>
<field name="friends" collection="arraylist" type="java.lang.String">
<bind-xml name="friends" node="element"/>
</field>
</class>
</mapping>

这是运行代码:

package CastorTest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
/**
* 使用配置文件进行javaBean和xml的转化
* @author issuser
*
*/
public class CastorUtil
{
private static final String filePath=new File("").getAbsolutePath()+"\\src\\CastorTest\\";
private static Mapping loadMapping(){
Mapping mapping=new Mapping();
try
{
mapping.loadMapping(filePath+"Mapping.xml");
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MappingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return mapping;
}
@org.junit.Test
public void Test(){
CastorUtil test=new CastorUtil();
try
{
//            test.beanToXml();
test.readXmlToBean();
} catch (MarshalException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ValidationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MappingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void beanToXml() throws IOException, MarshalException, ValidationException, MappingException{
List friend=new ArrayList();
friend.add("zhangsan");
friend.add("lisi");
Map score=new HashMap();
score.put("1", "za");
score.put("2", "na");
String[] hobby={"a","b"};
UserBean user=new UserBean();
user.setName("fenghao");
user.setAge("24");
user.setFriends(friend);
user.setHobby(hobby);
user.setScore(score);

File file=new File(filePath+"test.xml");
Writer writer=new FileWriter(file);
Marshaller shaller=new Marshaller(writer);
shaller.setEncoding("utf-8");
shaller.setMapping(CastorUtil.loadMapping());
shaller.marshal(user);
writer.flush();
writer.close();

}
public void readXmlToBean() throws MappingException, IOException, MarshalException, ValidationException{
String xmlString=FileUtil.readFile1(filePath+"test.xml");
Reader read=new StringReader(xmlString);
Unmarshaller unshaller=new Unmarshaller(UserBean.class);
unshaller.setMapping(CastorUtil.loadMapping());
UserBean user=(UserBean)unshaller.unmarshal(read);
System.out.println(user.getName()+"--name--"+user.getAge()+"--age--");
read.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: