JAXB转变对象到xml
发布时间:2020-12-15 22:36:21 所属栏目:百科 来源:网络整理
导读:?? 比较常用的几个: @XmlRootElement:根节点 @XmlAttribute:该属性作为xml的attribute @XmlElement:该属性作为xml的element,且可以增加属性(name="NewElementName"),那么生成的xml串的elment的标签是NewElementName 处理子类用两种方法: 处理子类1:
??
比较常用的几个:
@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();
??
??
??
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |