定义
做webservice的时候要解析xml,通过查找发现JAXB是可以解析xml并转换成对象的
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="标签名称", propOrder={属性名称})
@XmlRootElement
public class OrderRequestMsgHeader {
/**
*@XmlElement里面的name跟xml里面节点内的标签对应
*/
@XmlElement(name="msgHeader", required=true)
private MsgHeader msgHeader;
@XmlElement(name="ORDER_CODE", required=true)
private String orderCode;
get()/set()
}
MsgHeader类:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="msgHeader", propOrder={"USERNAME","PAGESIZE","CURRENT_PAGE"})
@XmlRootElement(name="msgHeader")
public class MsgHeader {
@XmlElement(name="USERNAME",required = true)
private String USERNAME;
@XmlElement(name="PAGESIZE",required = true)
private String PAGESIZE;
@XmlElement(name="CURRENT_PAGE",required = true)
private String CURRENT_PAGE;
get()/set()
}
数据
这是传过来的xml格式的数据,标签中orderRequestMsgHeader对应的是@XmlType中的name,msgHeader对应的就是@XmlElement中的名称
String xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<orderRequestMsgHeader>\r"+
"<msgHeader>\r" +
"<USERNAME>***有限公司</USERNAME>\r" +
"<PAGESIZE>50</PAGESIZE>\r" +
"<CURRENT_PAGE>1</CURRENT_PAGE>\r" +
"</msgHeader>\r"+
"<ORDER_CODE>000051</ORDER_CODE>\r"
"</orderRequestMsgHeader>";
通过JAXB解析Xml文件
解析
OrderRequestMsgHeader header=new OrderRequestMsgHeader();//要转换未的类信息
JAXBContext jaxbContext = JAXBContext.newInstance(OrderRequestMsgHeader.class);//创建JAXBContext对象,注意一定要传@XmlRootElement的所标记的类的类型
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();//拿到xml解析对象
StringReader sr = new StringReader(xml);
header = (OrderRequestMsgHeader)unmarshaller.unmarshal(sr);//转换后的对象信息
]
解析后的header:OrderRequestMsgHeader [msgHeader=MsgHeader{ USERNAME='纸业有限公司', SUBMITDATE='2020-01-01 12:12:12', PAGESIZE='50', CURRENT_PAGE='1', }, orderCode=000051