使用schema定义Model
好处:对象关联关系非常清晰
student.xsd
<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/test" xmlns:tns="http://www.example.org/test" elementFormDefault="qualified"> <element name="student" type="tns:Student"/> <complexType name="Student"> <sequence> <element name="name" type="string"/> <element name="sex" type="tns:Sex"></element> </sequence> </complexType> <!-- 类型定义可以抽取到一个xsd中进行定义,然后让其它xsd引入使用 --> <simpleType name="Sex"> <restriction base="string"> <enumeration value="mail"/> <enumeration value="femail"/> </restriction> </simpleType> </schema>
class.xsd
<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/test" xmlns:tns="http://www.example.org/test" elementFormDefault="qualified"> <!-- targetNamespace,即为java的包结构 --> <!-- 1.student.xsd与class.xsd的命名空间名称需要相同 2.使用include导入其它xsd --> <include schemaLocation="student.xsd"></include> <element name="class" type="tns:Class"/> <complexType name="Class"> <sequence> <element name="grade" type="int"/> <element name="name" type="string"/> <sequence maxOccurs="unbounded"> <element name="student" type="tns:Student"/> </sequence> </sequence> </complexType> </schema>
定义好之后,使用java内置的xjc名称将xsd转换为JAVA文件
即可得到我们需要的Model
xjc -d e:/xjc -verbose E:\project\spring\xsd\src\main\class.xsd
注意:xjc命令默认不会给生成的java对象加@XmlRootElement
使用JAXB完成JAVA对象与XML的转换:
marshaller: POJO--->XML
unmarshaller: XML--->POJO
package org.example.test;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class Test {
public static void main(String[] args) throws JAXBException {
Student stu = new Student();
stu.setName("zs");
stu.setSex(Sex.FEMAIL);
JAXBContext ctx = JAXBContext.newInstance(Student.class);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty("jaxb.encoding", "GBK");//设置编码
marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);//格式化输出
//marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);//去掉xml头部
marshaller.marshal(stu, System.out);
}
}
输出:
<?xml version="1.0" encoding="GBK" standalone="yes"?> <student xmlns="http://www.example.org/test"> <name>zs</name> <sex>femail</sex> </student>
问题:
如何把 standalone="yes"? 去掉呢?网上找的方法不行,我用的JDK7!