XML字符和bean的相互处理
XML字符和java bean的相互转换处理,在项目中经常会用到xml,需要将java bean转换成xml字符,也需要将xml字符转换成java bean。下面直接用代码介绍jdk自带的JAXBContext如何处理xml和bean的相互转换。是一种比较简单的处理方式。
/**
将xml字符转换成java对象
@param xmlStr
@param T
@return
*/
@SuppressWarnings({“rawtypes”, “unchecked”})
private static T xmlStringToBean(String xmlStr, Class T) throws Exception {
JAXBContext context = JAXBContext.newInstance(T);
Unmarshaller unmarshaller = context.createUnmarshaller();
return (T)unmarshaller.unmarshal(new StringReader(xmlStr));
}
/**
将java bean 转换成xml字符串
@param jaxbElement
@param classesToBeBound
@return
@throws Exception
*/
@SuppressWarnings(“rawtypes”)
private static String beanToXMLStr(Object jaxbElement, boolean isFormatted, Class… classesToBeBound) throws Exception {
JAXBContext context = JAXBContext.newInstance(classesToBeBound); // 获取上下文对象
Marshaller marshaller = context.createMarshaller(); // 根据上下文获取marshaller对象
marshaller.setProperty(Marshaller.JAXB_ENCODING, “UTF-8”); // 设置编码字符集
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, isFormatted); // 格式化XML输出,有分行和缩进
ByteArrayOutputStream baos = new ByteArrayOutputStream();
marshaller.marshal(jaxbElement, baos);
String xmlStr = new String(baos.toByteArray()); // 生成XML字符串
return xmlStr;
}
/**
将xml字符串写入到文件里
@param xmlStr
@throws Exception
*/
private static void writeXmlStrToFile(String xmlStr) throws Exception {
FileOutputStream fos = new FileOutputStream(“F:\xml\userbean.xml”);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(xmlStr);
bw.flush();
bw.close();
fos.close();
}
上面三个方法就可以实现xml和bean的相互转换,以及将xml写入文件中。
具体的bean定义也是有一定的形式要求的,如下:
如上四个图所示,要转换成xml字符串的是UserBean这个类。
1、@XmlRootElement(name = “userBean”) 这是定义xml的根元素。
2、userPhones定义了一个UserPhones的类,而不是直接在UserBean里直接定义List userPhone,这是因为直接定义集合的话,生成的xml将无法体现成集合的上下级形式。
3、@XmlElement(name = “user_address”) 这里是定义xml的一个元素,可以指定元素名。
4、@XmlAttribute 这里定义成这个,是将bean里的这个属性以xml根元素的一个属性的形式显示。
测试类:
public static void main(String[] args) {
UserPhone userPhone1 = new UserPhone(1, “13256899658”);
UserPhone userPhone2 = new UserPhone(2, “0755123456”);
List userPhoneList = new ArrayList<>();
userPhoneList.add(userPhone1);
userPhoneList.add(userPhone2);
UserPhones userPhones = new UserPhones(userPhoneList);
UserAddress userAddress = new UserAddress(“南山区白石洲”, “南山区高新园”);
UserBean userBean = new UserBean(“1.0.0”, “核核”, 28, userPhones, userAddress);
try {
String xmlStr = beanToXMLStr(userBean, true, UserBean.class, UserPhones.class, UserAddress.class, UserPhone.class);
System.out.println(xmlStr);
UserBean bean = xmlStringToBean(xmlStr, UserBean.class);
System.out.println(bean.toString());
for(UserPhone phone : bean.getUserPhones().getUserPhone()) {
System.out.println(phone);
}
writeXmlStrToFile(xmlStr);
System.out.println(“write xml success”);
} catch (Exception e) {
e.printStackTrace();
}
}
输出内容如下: