Jaxb annotation preliminary use

Source: Internet
Author: User
Tags xml attribute

I. jaxb common annotation for Java object and XML Conversion:

  1. @ Xmltype
  2. @ Xmlelement
  3. @ Xmlrootelement
  4. @ Xmlattribute
  5. @ Xmlaccessortype
  6. @ Xmlaccessororder
  7. @ Xmltransient
  8. @ Xmljavatypeadapter
Ii. Common annotation instructions

  1. @ Xmltype

@ Xmltype is used in class annotations and is often used with @ xmlrootelement and @ xmlaccessortype. It has three attributes: name, proporder, and namespace. The first two attributes are often used. For example:

@XmlType(name = "basicStruct", propOrder = {    "intValue",    "stringArray",    "stringValue")
When using the @ xmltype proporder attribute, all attributes in the JavaBean object must be listed; otherwise, an error is returned.
2. @ xmlelement

@ Xmlelement maps Java object attributes to XML nodes. When @ xmlelement is used, you can use the name attribute to change the name displayed by Java object attributes in XML. For example:

@ Xmlelement (name = "Address") Private string youraddress; 3. @ xmlrootelement

@ Xmlrootelement is used for class-level annotation, which corresponds to the XML and elements, often
@ Xmltype and @ xmlaccessortype. For example:

@ Xmltype
@ Xmlaccessortype (xmlaccesstype. Field)
@ Xmlrootelement
Public Class address {} 4. @ xmlattribute is used to map the attributes of a Java object to XML attributes, and you can use the name attribute to specify an alias for the generated XML Attribute. For example: @ xmlattribute (name = "country ")
Private string state; 5. @ xmlaccessortype

@ Xmlaccessortype specifies the access method to Java object attributes when an XML file is generated by a Java object. It is often used with @ xmlrootelement and @ xmltype. Its Attribute value is the four enumerated values of xmlaccesstype, which are divided:

Xmlaccesstype. Field: All member variables in the Java object

Xmlaccesstype. Property: all the member variables in the Java object accessed through getter/setter

Xmlaccesstype. public_member: member variables of all public access permissions in the Java object and member variables accessed through getter/setter

Xmlaccesstype. None: all attributes of the Java object are not mapped to XML elements.

Note: The default access level of @ xmlaccessortype is xmlaccesstype. public_member. Therefore, if the private member variable in the Java object sets the getter/setter method with the public permission, do not use the @ xmlelement and @ xmlattribute annotations on the private variable, otherwise, the same attribute has two errors in the Java class when the Java object generates XML. Similarly, if the access permission of @ xmlaccessortype is xmlaccesstype. None, And the @ xmlelement or @ xmlattribute annotation is used on Java member variables, these member variables can still be mapped to XML files.

6. @ xmlaccessororder

@ Xmlaccessororder is used to sort the XML elements generated by Java objects. It has two property values:

Accessororder. Alphabetical: sorts the generated XML elements in alphabetical order.

Xmlaccessorder. undefined: unordered

7. @ xmltransient

@ Xmltransient indicates that this attribute is ignored when the Java object maps to XML. That is, this element is not displayed in the generated XML file.

8. @ xmljavatypeadapter

@ Xmljavatypeadapter is often used to convert complex objects, such as map type or formatting date. When using this annotation, you need to write an adapter class to inheritXmladapter abstract class and implement the methods in it.

@ Xmljavatypeadapter (value = xxx. Class), value is your own adapter class

Xmladapter:

public abstract class XmlAdapter<ValueType,BoundType> {    // Do-nothing constructor for the derived classes.    protected XmlAdapter() {}    // Convert a value type to a bound type.    public abstract BoundType unmarshal(ValueType v);    // Convert a bound type to a value type.    public abstract ValueType marshal(BoundType v); }
Iii. Example

1. Shop. Java

package jaxb.shop;import java.util.Set;import javax.xml.bind.annotation.XmlAccessOrder;import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlType;import javax.xml.bind.annotation.XmlElementWrapper;import javax.xml.bind.annotation.XmlAccessorOrder;@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)@XmlAccessorType(XmlAccessType.FIELD)@XmlType(name = "shop", propOrder = { "name", "number", "describer", "address","orders" })
@ Xmlrootelement (name = "chmart") public class shop {@ xmlattributeprivate string name; // @ xmlelementprivate string number; @ xmlelementprivate string Describer; @ xmlelementwrapper (name = "orders ") @ xmlelement (name = "order") private set <order> orders; @ xmlelementprivate Address; public shop () {} public shop (string name, string number, string Describer, address) {This. name = Name; this. number = number; this. describer = Describer; this. address = address;} getter/setter
// @ Xmltype (proporder = {}) and @ xmlaccessororder (xmlaccessorder. Alphabetical) are used at the same time, but the generated XML only generates elements in the order defined by proporder.

2. Order. Java

package jaxb.shop;import java.math.BigDecimal;import java.util.Date;import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlType;import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;@XmlType(name="order",propOrder={"shopName","orderNumber","price","amount","purDate","customer"})@XmlAccessorType(XmlAccessType.FIELD)@XmlRootElementpublic class Order {//@XmlElement  private String shopName;@XmlAttributeprivate String orderNumber;//@XmlElement@XmlJavaTypeAdapter(value=DateAdapter.class)private Date purDate;//@XmlElementprivate BigDecimal price;//@XmlElementprivate int amount;//@XmlElementprivate Customer customer;public Order() {}public Order(String shopName, String orderNumber, Date purDate,BigDecimal price, int amount) {this.shopName = shopName;this.orderNumber = orderNumber;this.purDate = purDate;this.price = price;this.amount = amount;}
Getter/setter
// @ Xmlaccessortype (xmlaccesstype. Field), so @ xmlelement is commented out here. These elements will still be generated in XML

3. Customer. Java

package jaxb.shop;import java.util.Set;import javax.xml.bind.annotation.XmlType;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;@XmlType@XmlAccessorType(XmlAccessType.FIELD)@XmlRootElementpublic class Customer {@XmlAttributeprivate String name;private String gender;private String phoneNo;private Address address;private Set<Order> orders;public Customer() {}public Customer(String name, String gender, String phoneNo, Address address) {this.name = name;this.gender = gender;this.phoneNo = phoneNo;this.address = address;}
Getter/setter

4. Address. Java

package jaxb.shop;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlType;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlAccessOrder;import javax.xml.bind.annotation.XmlAccessorOrder;@XmlType(propOrder={"state","province","city","street","zip"})@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)@XmlAccessorType(XmlAccessType.NONE)@XmlRootElementpublic class Address {@XmlAttribute private String state;@XmlElementprivate String province;@XmlElementprivate String city;@XmlElementprivate String street;@XmlElementprivate String zip;public Address() {super();}public Address(String state, String province, String city, String street,String zip) {super();this.state = state;this.province = province;this.city = city;this.street = street;this.zip = zip;}
Getter/setter
// Note: Although @ xmlaccessortype is xmlaccesstype. None, after the @ xmlattribute and @ xmlelement annotations are added to the private attributes of the Java class, these private members map to generate XML elements.

5. dateadapter. Java

package jaxb.shop;import java.util.Date;import java.text.SimpleDateFormat;import javax.xml.bind.annotation.adapters.XmlAdapter;public class DateAdapter extends XmlAdapter<String, Date> {private String pattern = "yyyy-MM-dd HH:mm:ss";SimpleDateFormat fmt = new SimpleDateFormat(pattern);@Overridepublic Date unmarshal(String dateStr) throws Exception {return fmt.parse(dateStr);}@Overridepublic String marshal(Date date) throws Exception {return fmt.format(date);}}
// Used to format the display format of a date in XML. When the XML unmarshal is a Java object, the string is parsed as a date object.

6. shoptest. Java

package jaxb.shop;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.math.BigDecimal;import java.util.Date;import java.util.HashSet;import java.util.Set;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;public class ShopTest {public static void main(String[] args) throws JAXBException, IOException{Set<Order> orders = new HashSet<Order>();Address address1 = new Address("China", "ShangHai", "ShangHai", "Huang", "200000");Customer customer1 = new Customer("Jim", "male", "13699990000", address1);Order order1 = new Order("Mart", "LH59900", new Date(), new BigDecimal(60), 1);order1.setCustomer(customer1);Address address2 = new Address("China", "JiangSu", "NanJing", "ZhongYangLu", "210000");Customer customer2 = new Customer("David", "male", "13699991000", address2);Order order2 = new Order("Mart", "LH59800", new Date(), new BigDecimal(80), 1);order2.setCustomer(customer2);orders.add(order1);orders.add(order2);Address address3 = new Address("China", "ZheJiang", "HangZhou", "XiHuRoad", "310000");Shop shop = new Shop("CHMart", "100000", "EveryThing",address3);shop.setOrder(orders);FileWriter writer = null;JAXBContext context = JAXBContext.newInstance(Shop.class);try {Marshaller marshal = context.createMarshaller();marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);marshal.marshal(shop, System.out);writer = new FileWriter("shop.xml");marshal.marshal(shop, writer);} catch (Exception e) {e.printStackTrace();}Unmarshaller unmarshal = context.createUnmarshaller();FileReader reader = new FileReader("shop.xml") ;Shop shop1 = (Shop)unmarshal.unmarshal(reader);Set<Order> orders1 = shop1.getOrder();for(Order order : orders1){System.out.println("***************************");System.out.println(order.getOrderNumber());System.out.println(order.getCustomer().getName());System.out.println("***************************");}}}

7. generated XML file

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><CHMart name="CHMart">    <number>100000</number>    <describer>EveryThing</describer>    <address state="China">        <province>ZheJiang</province>        <city>HangZhou</city>        <street>XiHuRoad</street>        <zip>310000</zip>    </address>    <orders>        <order orderNumber="LH59800">            <shopName>Mart</shopName>            <price>80</price>            <amount>1</amount>            <purDate>2012-03-25 12:57:23</purDate>            <customer name="David">                <gender>male</gender>                <phoneNo>13699991000</phoneNo>                <address state="China">                    <province>JiangSu</province>                    <city>NanJing</city>                    <street>ZhongYangLu</street>                    <zip>210000</zip>                </address>            </customer>        </order>        <order orderNumber="LH59900">            <shopName>Mart</shopName>            <price>60</price>            <amount>1</amount>            <purDate>2012-03-25 12:57:23</purDate>            <customer name="Jim">                <gender>male</gender>                <phoneNo>13699990000</phoneNo>                <address state="China">                    <province>ShangHai</province>                    <city>ShangHai</city>                    <street>Huang</street>                    <zip>200000</zip>                </address>            </customer>        </order>    </orders></CHMart>

The preceding example uses a simple shop order model.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.