JDK中JAXB相关的重要Class和Interface:
JAXBContext类,是应用的入口,用于管理XML/Java绑定信息。
- Marshaller接口,将Java对象序列化为XML数据。
- Unmarshaller接口,将XML数据反序列化为Java对象。
JDK中JAXB相关的重要Annotation:
- @XmlType,将Java类或枚举类型映射到XML模式类型(可以指定xml各个字段的顺序)
- @XmlAccessorType(XmlAccessType.FIELD) ,控制字段或属性的序列化。FIELD表示JAXB将自动绑定Java类中的每个非静态的(static)、非瞬态的(由@XmlTransient标注)字段到XML。其他值还有XmlAccessType.PROPERTY和XmlAccessType.NONE。
- @XmlAccessorOrder,控制JAXB 绑定类中属性和字段的排序。
- @XmlJavaTypeAdapter,使用定制的适配器(即扩展抽象类XmlAdapter并覆盖marshal()和unmarshal()方法),以序列化Java类为XML。
- @XmlElementWrapper ,对于数组或集合(即包含多个元素的成员变量),生成一个包装该数组或集合的XML元素(称为包装器)。
- @XmlRootElement,将Java类或枚举类型映射到XML元素。
- @XmlElement,将Java类的一个属性映射到与属性同名的一个XML元素。
- @XmlAttribute,将Java类的一个属性映射到与属性同名的一个XML属性。
其他:
- 对于要序列化(marshal)为XML的Java类,绝不能把成员变量声明为public,否则运行将抛出异常com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException。
- 对于JAXB相关的重要Annotation的声明,如@Xml.....,可以放在成员变量的setter()或getter()方法上,两者中任选其一即可,但决不能放在成员变量上,否则运行将抛出异常com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException。
本文先介绍Marshaller和unMarshaller的使用,标签后边文章再介绍
工具类代码:
package com.javax.xml;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import com.bean.Student;
public class XmlUtils {
public static void main(String[] args) throws JAXBException {
//创建实例对象
Map<String, Integer> reportMap=new HashMap<String, Integer>();
reportMap.put("语文",99);
reportMap.put("数学",99);
reportMap.put("英语",99);
Student student=new Student(0, "刘阿姨", false, 29,reportMap);
//对象转字符串
String xmStr=beanToXml(student);
System.out.println(xmStr);
//对象转xml文件
beanToXmlFile(student, "student.xml");
//xml字符串转对象
Student student2 =(Student) xmltoBean(xmStr,Student.class);
System.out.println(student2.toString());
//xml文件转对象
Student student3 =(Student) xmlFiletoBean("student.xml",Student.class);
System.out.println(student3.toString());
}
/**
* 对象转xml字符串
* @param object
* @return
* @throws JAXBException
*/
public static String beanToXml( Object object) throws JAXBException{
StringWriter stringWriter=new StringWriter();
JAXBContext jaxbContext=JAXBContext.newInstance(object.getClass());
Marshaller marshaller=jaxbContext.createMarshaller();
marshaller.marshal(object, stringWriter);
return stringWriter.toString();
}
/**
* @ 对象转格式化xml字符串
* @param object 实例对象
* @return xml字符串
* @throws JAXBException
*/
public static String beanToperrtyXml( Object object) throws JAXBException{
StringWriter stringWriter=new StringWriter();
JAXBContext jaxbContext=JAXBContext.newInstance(object.getClass());
Marshaller marshaller=jaxbContext.createMarshaller();
//格式化xml
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//去掉报文头
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.marshal(object, stringWriter);
return stringWriter.toString();
}
/**
* @ 对象转xml字符串
* @param object 实例对象
* @return xml字符串
* @throws JAXBException
*/
public static void beanToXmlFile( Object object,String filepath) throws JAXBException{
File file=new File(filepath);
JAXBContext jaxbContext=JAXBContext.newInstance(object.getClass());
Marshaller marshaller=jaxbContext.createMarshaller();
//设置编码格式
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//格式化xml
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(object, file);
}
/**
* @字符串反序列化为对象
* @param <T>
* @param xmlStr
* @param clazz
* @return
* @throws JAXBException
*/
public static <T> Object xmltoBean (String xmlStr,Class<T> clazz) throws JAXBException {
StringReader stringReader=new StringReader(xmlStr);
JAXBContext jaxbContext=JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller=jaxbContext.createUnmarshaller();
Object object=unmarshaller.unmarshal(stringReader);
return object;
}
/**
* @xml文件反序列化为对象
* @param <T>
* @param filepath
* @param clazz
* @return
* @throws JAXBException
*/
public static <T> Object xmlFiletoBean (String filepath,Class<T> clazz) throws JAXBException {
File file=new File(filepath);
JAXBContext jaxbContext=JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller=jaxbContext.createUnmarshaller();
Object object=unmarshaller.unmarshal(file);
return object;
}
}
实体类javabean:
package com.bean;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import sun.font.TrueTypeFont;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="Student")
public class Student{
//学号
@XmlElement(name="id",required =true)
int id;
//姓名
@XmlElement(name="name",required =true)
String name;
//性别
@XmlElement(name="sex",required =true)
boolean sex;
//年龄
@XmlElement(name="age",required =true)
int age;
//成绩单
@XmlElement
Map<String, Integer> reportMap;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(int id, String name, boolean sex, int age, Map<String, Integer> reportMap) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
this.reportMap = reportMap;
}
public Student() {
super();
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + ", reportMap=" + reportMap
+ "]";
}
}
执行结果:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Student><id>0</id><name>刘阿姨</name><sex>false</sex><age>29</age><reportMap><entry><key>数学</key><value>99</value></entry><entry><key>语文</key><value>99</value></entry><entry><key>英语</key><value>99</value></entry></reportMap></Student>
Student [id=0, name=刘阿姨, sex=false, age=29, reportMap={数学=99, 语文=99, 英语=99}]
Student [id=0, name=刘阿姨, sex=false, age=29, reportMap={数学=99, 语文=99, 英语=99}]
文件结果:
Marshaller参数设置作用
- //设置编码格式 marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK");
- //格式化xml marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- //去掉报文头 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
xsi:schemaLocation和xsi:noNamespaceSchemaLocation,前者用于声明了目标名称空间的模式文档,后者用于没有目标名称空间的模式文档,
它们通常在实例文档中使用 参考文章:https://blog.youkuaiyun.com/zhengyeqing520/article/details/6091656
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "schemaname"); marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "sss");后边两个属性一般不会用;