尝试过dom4j和XStream,二者对于XML转java bean都比较无力。最终JAXB解烦忧。
主要问题出现在构建pojo类上:
*出现在XML里的标签,都应该是pojo中的字段名。
*List都以数组形式表达,数组的字段名变成每一个元素的标签名。
<ALL>
<PNRNO />
<PASSENGERLIST>
<PASSENGER>
<NAME>1</NAME>
</PASSENGER>
<PASSENGER>
<NAME>2</NAME>
</PASSENGER>
<PASSENGER>
<NAME>3</NAME>
</PASSENGER>
</PASSENGERLIST>
</ALL>
应表示为
@XmlRootElement(name = "ALL")
public class ALL {
@XmlElement
public PassengerList PASSENGERLIST;
@XmlRootElement
public static class PassengerList {
@XmlElement
Passenger[] PASSENGER;
}
}
注解使用参考:
http://blog.csdn.net/chen7788/article/details/7384315
http://blog.csdn.net/czplplp_900725/article/details/7888896
JAXB实现XML和java bean的互转:
/**
* 将Java对象序列化为XML字符串
*
* @param pojo 待序列化的Java对象
* @throws JAXBException
* @return
*/
public static String toXml(Object pojo) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(pojo.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); //编码格式
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //是否格式化生成的XML
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false); // 是否省略XML头声明信息
StringWriter stringWriter = new StringWriter();
marshaller.marshal(pojo, stringWriter);
return stringWriter.toString();
}
/**
* 将XML字符串反序列化为Java对象
*
* @param xmlStr 待反序列化的XML字符串
* @param pojoClass 需要反序列化的类型
* @throws JAXBException
* @return
*/
public static <T> Object fromXml(String xmlStr, Class<T> pojoClass) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(pojoClass);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Object object = unmarshaller.unmarshal(new ByteArrayInputStream(xmlStr.getBytes()));
return object;
}