JAXB转变对象到xml

来源:互联网 发布:mac版本老装不了xcode 编辑:程序博客网 时间:2024/06/17 22:29

   比较常用的几个:
       @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;// 航班唯一IDprivate 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 stubV2FlightInfo 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");// 是否格式化生成的XMLjaxbMarshaller.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();





0 0
原创粉丝点击