您的位置:首页 > 编程语言 > Java开发

不需要@XmlRootElement如何使用JAXB解组javabean

2015-10-22 22:06 477 查看
很多资料说,使用JAXB将XML转换为javabean时必须在javabean上增加@XmlRootElement注解,现在找到了一种不需要增加注解的方式,代码如下:

假如XML格式如:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<ns3:Person xsi:schemaLocation="s" xsi:noNamespaceSchemaLocation="w"

xmlns:ns3="http://ws.test.com"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<datasetCode>111</datasetCode>

<infoContent>222</infoContent>

<messageType>INF</messageType>

</ns3:Person>,

则解组代码如:

JAXBContext jc = JAXBContext.newInstance(ExchangeNotice.class);

Unmarshaller u = jc.createUnmarshaller();

StringReader reader = new StringReader(xml); //这里的xml是上边的xml字符串

XMLInputFactory xmlFactory = XMLInputFactory.newInstance();

XMLStreamReader reader2 = xmlFactory.createXMLStreamReader(reader);

JAXBElement userElement = u.unmarshal(reader2, ExchangeNotice.class); //这里是关键,需要传入目标对象

Object result = userElement.getValue(); //这里的result实际上就是ExchangeNotice的对象,可以直接强转。

没有什么技术含量,只是网上资料太少,这里总结下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: