XMLを解析するオプションのシナリオであるbetwinxt

7797 ワード

apcheのbetwinxtを使用すると、関連ライブラリはØcommons-beanutils.jar Ø      commons-betwixt-1.0-beta-1.jar Ø      commons-collections-3.2.1.jar Ø      commons-configuration-1.6.jar Ø      commons-digester.jar Ø      commons-lang-2.4.jar Ø      commons-logging.JArは、例えば、次のXMLを解析する.
 <?xml version="1.0" encoding="UTF-8" ?>
 <class id="1" name="class one">
    <students>
          <student name="Jime">
                  <score maths="80" />
             </student>
          <student name="Abby">
                    <score maths="100" />
       </student>
      </students>
  </class>

構造は簡単で,ここではbetwinxt方式を用いて解析を行う.まずXMLの要素情報をカプセル化し,主に3つのクラス:Class.java
public class Class {

       private int id;

       private String name;

       private List<Student> students = new ArrayList<Student>();

       /**
        * Add a student.
        * @param student
        */
       public void addStudent(Student student){
          this.students.add(student);
       }    

       /**
        * Remove a student.
        * @param student
        */
       public void removeStudent(Student student){
              this.students.remove(student);
       }

       /**
        * @return the id
        */

       public int getId() {
              return id;
       }

       /**
        * @param id the id to set
        */
       public void setId(int id) {
              this.id = id;
       }

       /**
        * @return the name
        */
       public String getName() {
              return name;
       }

       /**
        * @param name the name to set
        */
       public void setName(String name) {
              this.name = name;
       }

       /**
        * @return the students
        */
       public List<Student> getStudents() {
              return students;
       }

       /**
        * @param students the students to set
        */
       public void setStudents(List<Student> students) {
              this.students = students;
       }

}

 Student.java
public class Score {

       private int mathScore;

       /**
        * @return the mathScore
        */
       public int getMathScore() {
              return mathScore;
       }

       /**
        * @param mathScore the mathScore to set
        */
       public void setMathScore(int mathScore) {
              this.mathScore = mathScore;
       }

}

 
簡単なので、あまり説明する必要はありません.各クラスに対応するXML記述ファイル:Class.betwixt:
<?xml version="1.0" encoding="UTF-8"?>
<info primitiveTypes="attribute">
       <element name="class">
           <attribute name="id" property="id"/>
             <attribute name="name" property="name"/>
              <element name="students">
                 <element name="student" property="student"/>
              </element>           
              <addDefaults/>
       </element>
</info>

 Student.betwixt:
<?xml version="1.0" encoding="UTF-8"?>
<info primitiveTypes="attribute">
       <element name="student">
              <attribute name="name" property="name"/>      
              <element name="score" property="score"/>       
              <addDefaults/>
       </element>
</info>

 Score.betwixt:
<?xml version="1.0" encoding="UTF-8"?>
<info primitiveTypes="attribute">
       <element name="score">
              <attribute name="maths" property="mathScore"/>
              <addDefaults/>
       </element>
</info>

これらのXMLファイル名はクラス名と同じで、XMLファイルとエンティティクラスの間でマッピングするために使用されます.具体的な解析方法は簡単です.これらの書類に注意してください.JAvaファイルは同じディレクトリの下に配置されます.
 
public static Object fromXml(InputStream in, Class clazz)
                     throws XmlException {

              BeanReader beanReader = new BeanReader();
             Object object = null;
              try {
                     beanReader.registerBeanClass(clazz);
                    beanReader.getXMLIntrospector().setWrapCollectionsInElement(true);
                     object = beanReader.parse(in);
              } catch (Exception e) {
                     throw new XmlException(e);
              }
              return object;
       }

fromXml解析ファイルを使用するには、次の手順に従います.
public static Class parseFromXml(String path) throws Exception {

              FileInputStream in;
              Class obj = null;
              try {
                     in = new FileInputStream(path);
                     obj = (Class) XmlUtil.fromXml(in, Class.class);
              } catch (FileNotFoundException e) {
                     throw new Exception(e);
              } catch (Exception e) {
                     throw new Exception(e);
              }

              return obj;
       }

XMLとして出力:
public static void toXml(Object object, OutputStream out)
                     throws Exception {
              try {
                     BeanWriter beanWriter = new BeanWriter(out, "UTF-8");               
beanWriter.enablePrettyPrint();
beanWriter.setIndent("    ");                                              
beanWriter.setEndOfLine(System.getProperty("line.separator"));                   
beanWriter.writeXmlDeclaration("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");   
                  beanWriter.getXMLIntrospector().setWrapCollectionsInElement(true);
                     beanWriter.setWriteEmptyElements(false);
                     beanWriter.write(object);
                     beanWriter.close();
              } catch (Exception e) {
                     throw new XmlException(e);
              }
   }

ClassクラスのオブジェクトをXMLとして出力します.
public static void writeToXml(Object object, String path)
                     throws Exception {

              try {
                     FileOutputStream out = new FileOutputStream(path);
                     XmlUtil.toXml(object, out);
                     out.close();
              } catch (FileNotFoundException e) {
                     throw new Exception(e);
              } catch (IOException e) {
                     e.printStackTrace();
              }
       }

XML解析を完了する過程は簡単で、いくつかの文だけで、これは大型で複雑なXML解析に役立ち、自分で各種の属性、要素などを処理する必要はありません.JArファイルはカプセル化されています.