它要做到就是把xml到bean的互相轉(zhuǎn)換。
bean中稍微要注意點(diǎn)的地方:
1、bean要有默認(rèn)的構(gòu)造方法;
2、持久化的屬性要有相應(yīng)的get/set方法。
還有一個(gè)就是根據(jù)mapping來(lái)定義xml文檔的結(jié)構(gòu),和相應(yīng)的調(diào)整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() );
}
}
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();
}
/**
* 向文件中寫入內(nèi)容
*
* @param filepath
* 寫入文件的文件路徑
* @param write
* 寫入的內(nèi)容
* @param flag1
* 是否覆蓋,true-不覆蓋原來(lái)的內(nèi)容(追加),false-覆蓋原來(lái)的內(nèi)容
* @param flag2
* 是否換行,true-換行后寫入,false-直接在文件末尾寫入
* @throws IOException
*/
public static void writeFile( String filepath,
String str,
boolean flag1,
boolean flag2 ) throws IOException{
// 1.使用File類找到一個(gè)文件
File file = new File( filepath );
// 2.通過(guò)子類實(shí)例化父類對(duì)象
OutputStream out = null;// 準(zhǔn)備好一個(gè)輸出的對(duì)象
// flag1=true,追加;flag1=false,覆蓋
out = new FileOutputStream( file, flag1 );// 實(shí)例化
// 3.以循環(huán)的方式輸出
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;
}
}
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;
}
}
<?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標(biāo)簽指明需要映射的類
name是這個(gè)類的類名,需要指明類的全路徑
Map-to只有根元素對(duì)應(yīng)的類才配置這個(gè)屬性,指定的值為XML的根元素的名稱
Field 類字段和xml字段之間的映射 filed中的name是對(duì)應(yīng)類中字段的屬性名字 TYPE對(duì)應(yīng)的是屬性類型
Bind-xml 是xml文檔中對(duì)應(yīng)的字段信息,name、location是生成的XML元素的名稱,可以任意指定,建議盡量取得有意義
node指明是element還是attribute,默認(rèn)是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>