Search code examples
javaxmljaxbjaxb2

create nested structure using JAXB notations


<?xml version='1.0'?>
<info>
     <contract>
       <symbol>IBM</symbol>
       <sectype>STK</sectype>
       <exchange>SMART</exchange>
       <currency>USD</currency>
    </contract>
    <order>
      <action>SELL</action>
      <quantity>100</quantity>
      <ordertype>LMT</ordertype>
      <imtprice>imtprice</imtprice>
      <transmit>false</transmit>
   </order>
</info>

I want to use jaxb annotations with existing java classes to create above XML input but i don't know how create nested xml structure based on Java classes


Solution

  • Try this:

    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(propOrder = {"contract", "order"})
    public class Info {
    @XmlElement(required = true)
    private Contract contract;
    @XmlElement(required = true)
    private Order order; // Getters and setters
    }

    Another class:

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(propOrder = {"symbol", "sectype", "exchange", "currency"})
    public class Contract {
    @XmlElement(required = true)
    private String symbol;
    @XmlElement(required = true)
    private String sectype;
    @XmlElement(required = true)
    private String exchange;
    @XmlElement(required = true)
    private String currency;

    //Getters and setters
    }

    Create an order class the same way.