castor应用demo
它要做到就是把xml到bean的互相转换。bean中稍微要注意点的地方:
1、bean要有默认的构造方法;
2、持久化的属性要有相应的get/set方法。
还有一个就是根据mapping来定义xml文档的结构,和相应的调整xml格式的方法。
public
static
void
testMarshal()
throws
Exception{
Student bean = new Student( " Jack " );
List < Teacher > tcrList = new ArrayList < Teacher > ();
tcrList.add( new Teacher( " Miss Z " , " History " ) );
tcrList.add( new Teacher( " Miss X " , " English " ) );
bean.setTcrList( tcrList );
File file = new File( FILENAME );
Writer writer = new FileWriter( file );
Marshaller m = new Marshaller( writer );
Mapping mapping = new Mapping();
mapping.loadMapping( " mapping.xml " );
m.setMapping( mapping );
m.setEncoding( " utf-8 " );
m.marshal( bean );
// 1.读取student.xml文件
String unFormattedXml = CastorUtil.readFile( FILENAME );
// 2.格式化XML文件
String formattedXml = CastorUtil.formatXML( unFormattedXml );
// 3.写入到student.xml文件
CastorUtil.writeFile( FILENAME, formattedXml, false , false );
}
public static void testUnmarshal() throws Exception{
File file = new File( FILENAME );
Reader reader = new FileReader( file );
Mapping mapping = new Mapping();
mapping.loadMapping( " mapping.xml " );
Unmarshaller unmar = new Unmarshaller( mapping );
Student bean = (Student)unmar.unmarshal( reader );
System.out.println( bean.getName() );
List < Teacher > list = bean.getTcrList();
for ( Teacher t : list ){
System.out.println( t.getName() + " - " + t.getCourse() );
}
}
Student bean = new Student( " Jack " );
List < Teacher > tcrList = new ArrayList < Teacher > ();
tcrList.add( new Teacher( " Miss Z " , " History " ) );
tcrList.add( new Teacher( " Miss X " , " English " ) );
bean.setTcrList( tcrList );
File file = new File( FILENAME );
Writer writer = new FileWriter( file );
Marshaller m = new Marshaller( writer );
Mapping mapping = new Mapping();
mapping.loadMapping( " mapping.xml " );
m.setMapping( mapping );
m.setEncoding( " utf-8 " );
m.marshal( bean );
// 1.读取student.xml文件
String unFormattedXml = CastorUtil.readFile( FILENAME );
// 2.格式化XML文件
String formattedXml = CastorUtil.formatXML( unFormattedXml );
// 3.写入到student.xml文件
CastorUtil.writeFile( FILENAME, formattedXml, false , false );
}
public static void testUnmarshal() throws Exception{
File file = new File( FILENAME );
Reader reader = new FileReader( file );
Mapping mapping = new Mapping();
mapping.loadMapping( " mapping.xml " );
Unmarshaller unmar = new Unmarshaller( mapping );
Student bean = (Student)unmar.unmarshal( reader );
System.out.println( bean.getName() );
List < Teacher > list = bean.getTcrList();
for ( Teacher t : list ){
System.out.println( t.getName() + " - " + t.getCourse() );
}
}
package
com._castor;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class CastorUtil{
private static Document parseXMLFile( String in )
throws ParserConfigurationException,
SAXException,
IOException{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource( new StringReader( in ) );
return db.parse( is );
}
public static String formatXML( String unFormattedXml )
throws ParserConfigurationException,
SAXException,
IOException{
final Document document = parseXMLFile( unFormattedXml );
OutputFormat format = new OutputFormat( document );
format.setIndenting( true );
format.setLineWidth( 65 );
format.setIndent( 2 );
format.setEncoding( " utf-8 " );
Writer out = new StringWriter();
XMLSerializer serializer = new XMLSerializer( out, format );
serializer.serialize( document );
return out.toString();
}
public static String readFile( String filePath ) throws IOException{
StringBuffer fileContent = new StringBuffer();
File file = new File( filePath );
if ( file.isFile() && file.exists() ){
InputStreamReader read = new InputStreamReader( new FileInputStream( file ), " utf-8 " );
BufferedReader reader = new BufferedReader( read );
String line;
while ( ( line = reader.readLine() ) != null ){
fileContent.append( line );
}
reader.close();
read.close();
}
return fileContent.toString();
}
/**
* 向文件中写入内容
*
* @param filepath
* 写入文件的文件路径
* @param write
* 写入的内容
* @param flag1
* 是否覆盖,true-不覆盖原来的内容(追加),false-覆盖原来的内容
* @param flag2
* 是否换行,true-换行后写入,false-直接在文件末尾写入
* @throws IOException
*/
public static void writeFile( String filepath,
String str,
boolean flag1,
boolean flag2 ) throws IOException{
// 1.使用File类找到一个文件
File file = new File( filepath );
// 2.通过子类实例化父类对象
OutputStream out = null ; // 准备好一个输出的对象
// flag1=true,追加;flag1=false,覆盖
out = new FileOutputStream( file, flag1 ); // 实例化
// 3.以循环的方式输出
String result = "" ;
if ( flag1 ){
if ( flag2 ){
result = " \n " + str;
} else {
result = str;
}
} else {
result = str;
}
byte b[] = result.getBytes();
for ( int i = 0 ; i < b.length; i ++ ){
out.write( b[i] );
}
out.close();
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class CastorUtil{
private static Document parseXMLFile( String in )
throws ParserConfigurationException,
SAXException,
IOException{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource( new StringReader( in ) );
return db.parse( is );
}
public static String formatXML( String unFormattedXml )
throws ParserConfigurationException,
SAXException,
IOException{
final Document document = parseXMLFile( unFormattedXml );
OutputFormat format = new OutputFormat( document );
format.setIndenting( true );
format.setLineWidth( 65 );
format.setIndent( 2 );
format.setEncoding( " utf-8 " );
Writer out = new StringWriter();
XMLSerializer serializer = new XMLSerializer( out, format );
serializer.serialize( document );
return out.toString();
}
public static String readFile( String filePath ) throws IOException{
StringBuffer fileContent = new StringBuffer();
File file = new File( filePath );
if ( file.isFile() && file.exists() ){
InputStreamReader read = new InputStreamReader( new FileInputStream( file ), " utf-8 " );
BufferedReader reader = new BufferedReader( read );
String line;
while ( ( line = reader.readLine() ) != null ){
fileContent.append( line );
}
reader.close();
read.close();
}
return fileContent.toString();
}
/**
* 向文件中写入内容
*
* @param filepath
* 写入文件的文件路径
* @param write
* 写入的内容
* @param flag1
* 是否覆盖,true-不覆盖原来的内容(追加),false-覆盖原来的内容
* @param flag2
* 是否换行,true-换行后写入,false-直接在文件末尾写入
* @throws IOException
*/
public static void writeFile( String filepath,
String str,
boolean flag1,
boolean flag2 ) throws IOException{
// 1.使用File类找到一个文件
File file = new File( filepath );
// 2.通过子类实例化父类对象
OutputStream out = null ; // 准备好一个输出的对象
// flag1=true,追加;flag1=false,覆盖
out = new FileOutputStream( file, flag1 ); // 实例化
// 3.以循环的方式输出
String result = "" ;
if ( flag1 ){
if ( flag2 ){
result = " \n " + str;
} else {
result = str;
}
} else {
result = str;
}
byte b[] = result.getBytes();
for ( int i = 0 ; i < b.length; i ++ ){
out.write( b[i] );
}
out.close();
}
}
package
com._castor;
import java.util.List;
public class Student{
String name;
List < Teacher > tcrList;
public Student(){}
public Student( String name ){
this .name = name;
}
public String getName(){
return name;
}
public void setName( String name ){
this .name = name;
}
public List < Teacher > getTcrList(){
return tcrList;
}
public void setTcrList( List < Teacher > tcrList ){
this .tcrList = tcrList;
}
}
import java.util.List;
public class Student{
String name;
List < Teacher > tcrList;
public Student(){}
public Student( String name ){
this .name = name;
}
public String getName(){
return name;
}
public void setName( String name ){
this .name = name;
}
public List < Teacher > getTcrList(){
return tcrList;
}
public void setTcrList( List < Teacher > tcrList ){
this .tcrList = tcrList;
}
}
package
com._castor;
public class Teacher{
String name;
String course;
public Teacher(){}
public Teacher( String name, String course ){
this .name = name;
this .course = course;
}
public String getName(){
return name;
}
public void setName( String name ){
this .name = name;
}
public String getCourse(){
return course;
}
public void setCourse( String course ){
this .course = course;
}
}
public class Teacher{
String name;
String course;
public Teacher(){}
public Teacher( String name, String course ){
this .name = name;
this .course = course;
}
public String getName(){
return name;
}
public void setName( String name ){
this .name = name;
}
public String getCourse(){
return course;
}
public void setCourse( String course ){
this .course = course;
}
}
<?
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是这个类的类名,需要指明类的全路径
Map-to只有根元素对应的类才配置这个属性,指定的值为XML的根元素的名称
Field 类字段和xml字段之间的映射 filed中的name是对应类中字段的属性名字 TYPE对应的是属性类型
Bind-xml 是xml文档中对应的字段信息,name、location是生成的XML元素的名称,可以任意指定,建议尽量取得有意义
node指明是element还是attribute,默认是element
-->
< class name ="com._castor.Student" >
< map-to xml ="student-info" />
< field name ="name" type ="java.lang.String" >
< bind-xml name ="studentName" node ="attribute" />
</ field >
< field name ="tcrList" collection ="arraylist" type ="com._castor.Teacher" >
< bind-xml name ="teacher" />
</ field >
</ class >
< class name ="com._castor.Teacher" >
< field name ="name" type ="java.lang.String" >
< bind-xml name ="name" node ="attribute" />
</ field >
< field name ="course" type ="java.lang.String" >
< bind-xml name ="courseName" node ="element" />
</ field >
</ class >
</ mapping >
<! DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN" "http://castor.org/mapping.dtd" >
< mapping >
<!--
class标签指明需要映射的类
name是这个类的类名,需要指明类的全路径
Map-to只有根元素对应的类才配置这个属性,指定的值为XML的根元素的名称
Field 类字段和xml字段之间的映射 filed中的name是对应类中字段的属性名字 TYPE对应的是属性类型
Bind-xml 是xml文档中对应的字段信息,name、location是生成的XML元素的名称,可以任意指定,建议尽量取得有意义
node指明是element还是attribute,默认是element
-->
< class name ="com._castor.Student" >
< map-to xml ="student-info" />
< field name ="name" type ="java.lang.String" >
< bind-xml name ="studentName" node ="attribute" />
</ field >
< field name ="tcrList" collection ="arraylist" type ="com._castor.Teacher" >
< bind-xml name ="teacher" />
</ field >
</ class >
< class name ="com._castor.Teacher" >
< field name ="name" type ="java.lang.String" >
< bind-xml name ="name" node ="attribute" />
</ field >
< field name ="course" type ="java.lang.String" >
< bind-xml name ="courseName" node ="element" />
</ field >
</ class >
</ mapping >