首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

jAXB学习 (1)入门

2013-08-01 
jAXB学习 (一)入门这样就算安装成功了。?二、生成模型?安装完以后,就可以开始使用了,首先我们需要有一份sche

jAXB学习 (一)入门

这样就算安装成功了。

?

二、生成模型

?

安装完以后,就可以开始使用了,首先我们需要有一份schema文件,例如:

<?xml version="1.0" encoding="UTF-8"?><schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.liulutu.com/students/"    targetNamespace="http://www.liulutu.com/students/">    <element name="students">        <complexType>            <sequence>                <element name="student" type="tns:StudentType" maxOccurs="unbounded" />            </sequence>        </complexType>    </element>    <simpleType name="SexType">        <restriction base="string">            <enumeration value="Male"></enumeration>            <enumeration value="Female"></enumeration>        </restriction>    </simpleType>    <complexType name="StudentType">        <attribute name="sex" type="tns:SexType"></attribute>        <attribute name="name" type="string"></attribute>    </complexType></schema>

?

?

然后就可以根据这个schema文件生成对应的java模型类文件,可以到jaxb的bin目录下去,使用以下命令生成模型文件:xjc.bat?students.xsd?-d?src?-p?com.liulutu.student.model?

?

三、使用

?

有了以上模型文件后,就可以开始使用,例如

模型到XML
public class TestMarshaller {    public static void main(String[] args) throws JAXBException {        JAXBContext con = JAXBContext.newInstance("com.liulutu.student.model");        ObjectFactory factory = new ObjectFactory();        Students students = factory.createStudents();        addNewStudentTo(factory, students, "aaa", SexType.MALE);        addNewStudentTo(factory, students, "bbb", SexType.FEMALE);        Marshaller marshaller = con.createMarshaller();        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);        marshaller.marshal(students, new File("a.xml"));    }    private static void addNewStudentTo(ObjectFactory factory,            Students students, String name, SexType type) {        StudentType studentType = factory.createStudentType();        studentType.setName(name);        studentType.setSex(type);        students.getStudent().add(studentType);    }}

?

保存后的xml文件内容如下:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ns2:students xmlns:ns2="http://www.liulutu.com/students/">    <student name="aaa" sex="Male"/>    <student name="bbb" sex="Female"/></ns2:students>

?

?XML到模型

?以下代码用来还原以上保存的XML文件对应的模型(假如保存的文件名为a.xml):

public class TestUnmarshaller {    public static void main(String[] args) throws JAXBException {        JAXBContext con = JAXBContext.newInstance("com.liulutu.student.model");        Unmarshaller unmarshaller = con.createUnmarshaller();        Students students = (Students) unmarshaller.unmarshal(new File("a.xml"));        List<StudentType> student = students.getStudent();        Iterator<StudentType> iterator = student.iterator();        while(iterator.hasNext()){            StudentType next = iterator.next();            System.out.println(next.getName()+"  "+next.getSex());        }    }}

?

?

?

热点排行