简单介绍
JAXB是一项可以实现java对象与xml文件进行转换的技术。
涉及的几个类
(1)JAXBContext 理解为一个管理者
(2)Marshaller 将java对象写到文件里
(3)Unmarshaller 将xml解析为java对象
实例
实体类:
import java.io.Serializable;
import java.util.Locale;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ClientConfig")
@XmlAccessorType(XmlAccessType.FIELD)
public class ClientConfig implements Serializable{
private static final long serialVersionUID = 20131015L;
public static final String CONFIG_NAME = "ClientConfig";
@XmlElement(required = true)
private String code;
@XmlElement(required = true)
private String language;
@XmlElement(required = true)
private String country;
@XmlElement(required = true)
private boolean developMode;
@XmlElement(required = false,defaultValue="false")
private boolean testMode;
@XmlElement(required = true)
private String wsURL;
public String getCode() {
return code;
}
public String getLanguage() {
return language;
}
public String getCountry() {
return country;
}
public boolean isDevelopMode() {
return developMode;
}
public String getWsURL() {
return wsURL;
}
public boolean isTestMode() {
return testMode;
}
}
将对象写入到xml文件
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXB {
public static void main(String[] args) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(ClientConfig.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);//格式化输出的xml
marshaller.setProperty(Marshaller.JAXB_ENCODING,"UTF-8");// 设置输出编码,默认为UTF-8
ClientConfig c = new ClientConfig();
c.setXxx("er");//设置属性
marshaller.marshal(c,new File("path"));//path为文件路径
}
}
将xml文件解析为java对象
Reader reader = new FileReader(configFile);
JAXBContext context = JAXBContext.newInstance(ClientConfig.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
clientConfig = (ClientConfig)unmarshaller.unmarshal(reader);
小记
(1)@XmlRootElement,将Java类或枚举类型映射到XML元素;
(2)@XmlElement,将Java类的一个属性映射到与属性同名的一个XML元素;
(3)@XmlAttribute,将Java类的一个属性映射到与属性同名的一个XML属性;
注意事项:
(1)对于要序列化(marshal)为XML的Java类,绝不能把成员变量声明为public,否则运行将抛出异常
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException
(2)注解不能直接放在成员变量上,可以放在成员变量的getter或setter方法上,任选其一,否则也会抛出IllegalAnnotationsException异常
小结
本文为自己工作中遇到然后系统看了一下,其中也参考了此文章JavaEE学习之JAXB。