Jaxb技术进行xml和javabean对象之间互相转化.pdf
文本预览下载声明
Jaxb技术进行xml和j avabean对象之间互相转化
一、beanToXml
public static String convertToXml(Object obj, String encoding) {
String result = null;
try {
JAXBConte t conte t = JAXBConte t.newInstance(obj.getClass());
Marshaller marshaller = conte t.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); //省略头信息
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, 321); //scheam_location
marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, abc); //scheam_location
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
result = writer.toString();
} catch (E ception e) {
e.printStackTrace();
}
return result;
}
二、xmlToBean
public static T T converyToJavaBean(String ml, ClassT c) {
T t = null;
try {
JAXBConte t conte t = JAXBConte t.newInstance(c);
Unmarshaller unmarshaller = conte t.createUnmarshaller();
t = (T) unmarshaller.unmarshal(new StringReader( ml));
} catch (E ception e) {
e.printStackTrace();
}
return t;
}
三、使用注解
在Jaxb中常用的注解有
1. @XmlType
2. @XmlElement
3. @XmlRootElement
4. @XmlAttribute
5. @XmlAccessorType
6. @XmlAccessorOrder
7. @XmlTransient
8. @XmlJavaTypeAdapter
9. @XmlElementWrapper
10. @XmlList
11. @XmlSchema
12. @XmlValue
13. @XmlJavaTypeAdapter
1. @@XXmmllTTyyppee
@XmlType 注解用于标注类或枚举类型,用它标注的类在映射后的 schema 中中 以一个 XML 复杂数据类型的形式出现。我们可以通过
@XmlType 注解的 name 属性来定制映射的 XML 数据类型的名称,用 propOrder 属性来定制映射后
显示全部