JAXB转变对象到xml

前端之家收集整理的这篇文章主要介绍了JAXB转变对象到xml前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

比较常用的几个:
@XmlRootElement:根节点
@XmlAttribute:该属性作为xml的attribute
@XmlElement:该属性作为xml的element,且可以增加属性(name="NewElementName"),那么生成的xml串的elment的标签是NewElementName

处理子类用两种方法
处理子类1:利用@XmlSeeAlso({V2FlightInfo.class})加入子类名。
/**
 * @author zhangdapeng
 * @version 1.0,2014年6月9日
 * @since 1.0
 */
@XmlSeeAlso({V2FlightInfo.class})
public class FlightInfo {
//	@XmlElements({ @XmlElement(name = "c",type = V2FlightInfo.class),})
	private String soflSeqNr;// 航班唯一ID
	private String fltDt;// 航班日期
	private String fltNr;// 航班号
	private String opSuffix;// 航班号后缀
	private String alnCd;// 航空公司代码
	private String branchCode;// 分公司代码
	private String legSeqNr;// 航段序号
...
}

 
/**
 * @author zhangdapeng
 * @version 1.0,2014年6月10日
 * @since   1.0	
 */
public class V2FlightInfo extends FlightInfo {
	private String tmlBud="";

	public String getTmlBud() {
		return tmlBud;
	}

	public void setTmlBud(String tmlBud) {
		this.tmlBud = tmlBud;
	}

}
public static void main(String[] args) throws JAXBException {
		// TODO Auto-generated method stub
		
			V2FlightInfo re = new V2FlightInfo();
			// re.assignAllEmpty();
			re.setAcfOper("123");
			re.setActualAirborne("456");
			re.setActualLanding("");
			re.setTmlBud("tmlbud");

			List flightInfos = new ArrayList<FlightInfo>();
			flightInfos.add(re);

			re = new V2FlightInfo();
			// re.assignAllEmpty();
			re.setAcfOper("123");
			re.setActualAirborne("456");
			re.setActualLanding("");
			re.setTmlBud("tmlbud");
			flightInfos.add(re);

			JAXBContext jaxbContext = JAXBContext.newInstance(FlightInfos.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

			FlightInfos f = new FlightInfos();
			f.setFlightInfo(flightInfos);
			// 编码格式
			jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING,"utf-8");
			// 是否格式化生成的XML
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
			// 是否省略XML头信息<?xml version="1.0" encoding="gb2312" standalone="yes"?>
			jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT,true);
			// jaxbMarshaller.marshal(f,System.out);

			StringWriter writer = new StringWriter();

			jaxbMarshaller.marshal(f,writer);
			System.out.println( writer.toString());
			

	}

 
 
处理子类2:JAXBContext.newInstance(...),加入子类名,不用@XmlSeeAlso。
	JAXBContext jaxbContext = JAXBContext.newInstance(FlightInfos.class,V2FlightInfo.class);
		Marshaller jaxbMarshaller = jaxbContext.createMarshaller();





原文链接:https://www.f2er.com/xml/298351.html

猜你在找的XML相关文章