string类型的xml报文解析为java实体类object

回馈广大同行网友系列~首先thanks for 网友们的无私分享,在抄完之后我献上我的解决整理~~~~~
公司用内网,纯手打的
xml报文demo


<ROOT>
	<ITEM>
		<XXXX>XXXX>
		...
	ITEM>
	<ITEM>
		<XXXX>XXXX>
		...
	ITEM>
ROOT>

首先写一个XmlUtil工具类

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
...

public class XmlUtil{
	
	public static <T> T convertXmlStrToObject(Class<?> clazz,String xmlStr){
		T xmlObject = null;
		try{
			JAXBContext context = JAXBContext.newInstance(clazz);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			xmlObject = (T) unmarshaller.unmarshal(new StringReader(xmlStr));
		} catch (Exception e){
			log.error("将报文转换为object失败:{}",e.getMessage());
		}

		return xmlObject;
	}
}

你需要转化的类

@Data
@XmlRootElement(name = "ROOT")
public class XXXRoot{
	private List<XXX> ITEM;
}

ITEM对应了 < ITEM > 标签,如果要起别名可以试试@XmlElement(name = “ITEM”)我没试过,具体效果自己看吧

@XmlAccessorType(XmlAccessType.FIELD)
@Data
public class XXX implements Serializable{
	@XmlElement(name="yyy")
	private String yy;

	.....
}

使用的时候,XXXRoot ddd = XmlUtil.convertXmlStrToObject(XXXRoot.class,xmlbaowenstring);

你可能感兴趣的:(工作总结,java,xml,servlet)