Thursday, January 28, 2010

XML parsing using Castor

Put the castor-1.2.jar in you lib folder.
This is object to xml mapping.
 Example is given,
In this Students object is mapped to an xml.Each tag is mapped to different nodes in the XML.

Students.java
/**
 *
 */
package com.jijo;

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

/**
 * @author jijo
 *
 */
public class Students {
    private List<Student> students = new ArrayList<Student>();

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }
}

Student.java

package com.jijo;

public class Student {
    private String rollNo;
    private String name;
    private String className;
    public String getRollNo() {
        return rollNo;
    }
    public void setRollNo(String rollNo) {
        this.rollNo = rollNo;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getClassName() {
        return className;
    }
    public void setClassName(String className) {
        this.className = className;
    }
}







studentmapping.xml

 <?xml version="1.0"?>
<mapping>
    <class name="com.jijo.Students">
        <field name="students" type="com.jijo.Student" collection="collection">
            <bind-xml name="student" />    <!-- bind xml tag name -->
        </field>
    </class>  
  
    <class name="com.jijo.Student">
        <!--
        <field name="regNo" type="string">
            <bind-xml name="regNo" node="attribute" /> attribute parsing
        </field>
        -->
        <field name="rollNo" type="string">
            <bind-xml name="rollno"/>
        </field>
        <field name="name" type="string">
            <bind-xml name="name"/>
        </field>
      
        <field name="className" type="string">
            <bind-xml name="classname" />
        </field>
    </class>
</mapping>



XmlUtil.java
/**
 *
 */
package com.jijo;

import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.Unmarshaller;
import org.xml.sax.InputSource;



/**
 * @author jijo
 *
 */
public class XmlUtil {
    /**
     * This method will convert the data got from the data source to the appropriate
     * form for the next process.
     *
     * @param className
     * @param xmlFileName
     * @param mappingFileName
     * @throws Exception
     * @throws MappingException
     */
    public Object xmltoObject(String className, String xmlFileName, String mappingFileName) {
        Object obj = null;
        FileReader reader = null;
        try {

            // Load the mapping information from the file                               
            URL mappingURL =  getClass().getClassLoader().getResource(mappingFileName);                                               

            Mapping mapping=new Mapping();                                       
            mapping.loadMapping(mappingURL);                                       

            // Create a Reader to the file to unmarshal from
            reader = new FileReader(xmlFileName);

            // Unmarshal the data
            Unmarshaller unmarshaller = new Unmarshaller(Class
                    .forName(className));
            unmarshaller.setMapping(mapping);

            obj = (Object) unmarshaller.unmarshal(reader);

        } catch (Exception e) {
            e.printStackTrace();                          
           
        }
        finally {
            try {
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return obj;
    }
    /**
     * This method is used to cast the xml-string to object
     * @param className
     * @param xmlString
     * @param mappingFileName
     * @return
     */
    public Object xmlStringtoObject(String className,String xmlString,String mappingFileName) {
        ByteArrayInputStream Bis1=null;
        try {
            Bis1 = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e1) {

        }
        InputSource in = new InputSource();
        Object obj = null;
        try {

            // Load the mapping information from the file                               
            URL mappingURL =  getClass().getClassLoader().getResource(mappingFileName);

            Mapping mapping=new Mapping();
            mapping.loadMapping(mappingURL);
            // Create a Reader to the file to unmarshal from
            in.setByteStream(Bis1);
            // Unmarshal the data
            Unmarshaller unmarshaller = new Unmarshaller(Class
                    .forName(className));
            unmarshaller.setMapping(mapping);

            obj = (Object) unmarshaller.unmarshal(in);

        } catch (Exception e) {                                        
            e.printStackTrace();
        }
        finally {
            try {
                Bis1.close();
                Bis1=null;
                in=null;
            } catch (Exception e) {
                e.printStackTrace();                      
            }
        }
        return obj;
    }
}

Main.java










package com.jijo;

import java.util.List;


public class Main {
    public static void main(String[] args) {
        try{
            XmlUtil xmlUtil = new XmlUtil();
            Students obj = (Students) xmlUtil.xmltoObject("com.jijo.Students", "C:/jijo/xml/students.xml", "com/jijo/studentmapping.xml");
            if(obj != null){
                List<Student> students = obj.getStudents();
                if(students != null){
                    System.out.println("not null");
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}




 students.xml
<students>

<student>
<rollno>1</rollno>
<name>Jijo</name>
<classname>10</classname>
</student>

<student>
<rollno>2</rollno>
<name>Mathew</name>
<classname>10</classname>
</student>

<student>
<rollno>3</rollno>
<name>Ajeesh</name>
<classname>10</classname>
</student>

<student>
<rollno>4</rollno>
<name>Prathyush</name>
<classname>10</classname>
</student>

</students>


For more details visit http://www.castor.org.

No comments: