Natural

           

          castor應(yīng)用demo

          它要做到就是把xml到bean的互相轉(zhuǎn)換。
          bean中稍微要注意點的地方:
          1、bean要有默認的構(gòu)造方法;
          2、持久化的屬性要有相應(yīng)的get/set方法。

          還有一個就是根據(jù)mapping來定義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, falsefalse );
              }

              
          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-不覆蓋原來的內(nèi)容(追加),false-覆蓋原來的內(nèi)容
               * 
          @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;// 準(zhǔn)備好一個輸出的對象
                  
          // flag1=true,追加;flag1=false,覆蓋
                  out = new FileOutputStream( file, flag1 );// 實例化

                  
          // 3.以循環(huán)的方式輸出
                  String result = "";
                  
          if( flag1 ){
                      
          if( flag2 ){
                          result 
          = "\n" + str;
                      }
          else{
                          result 
          = str;
                      }
                  }
          else{
                      result 
          = str;
                  }

                  
          byte b[] = result.getBytes();
                  
          forint 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是這個類的類名,需要指明類的全路徑
              Map-to只有根元素對應(yīng)的類才配置這個屬性,指定的值為XML的根元素的名稱
              Field 類字段和xml字段之間的映射 filed中的name是對應(yīng)類中字段的屬性名字 TYPE對應(yīng)的是屬性類型
              Bind-xml 是xml文檔中對應(yīng)的字段信息,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>

          posted on 2012-08-22 17:06 此號已被刪 閱讀(333) 評論(0)  編輯  收藏 所屬分類: JAVA

          導(dǎo)航

          統(tǒng)計

          常用鏈接

          留言簿(8)

          隨筆分類(83)

          隨筆檔案(78)

          文章檔案(2)

          相冊

          收藏夾(7)

          最新隨筆

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 武义县| 乐清市| 衡南县| 西昌市| 四平市| 岑巩县| 大厂| 姜堰市| 乐昌市| 新宁县| 通州区| 穆棱市| 治县。| 牟定县| 建瓯市| 浮山县| 罗山县| 怀化市| 武川县| 庆阳市| 兴业县| 阿合奇县| 罗山县| 顺昌县| 桐乡市| 南江县| 区。| 霍林郭勒市| 英吉沙县| 资溪县| 石柱| 册亨县| 柞水县| 兴义市| 宜阳县| 淮北市| 高邑县| 牟定县| 双桥区| 武城县| 湖州市|