• java JAXB 学习


    JAXB(Java Architecture for XML Binding)是JDK的一部分,用于Object <-> XML的转换(有点类似于.NET中的XML序列化)。

    1、创建XSD

    可以使用任何工具生成XSD工具,比如XMLSPY。eclipse也提供了相关的jaxb插件,File -> New -> XML Schema File

    文件命名为order.xsd,eclipse中也提供了xsd可视化编辑工具

    当然,你要是很NB,对xsd结构倒背如流的话,完全也可以纯手写。

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!-- edited with XMLSpy v2013 (http://www.altova.com) by  () -->
     3 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
     4     <xs:element name="Order">
     5         <xs:annotation>
     6             <xs:documentation>Comment describing your root element</xs:documentation>
     7         </xs:annotation>
     8         <xs:complexType>
     9             <xs:sequence>
    10                 <xs:element name="OrderNo" type="xs:string"/>
    11                 <xs:element name="OrderDateTime" type="xs:dateTime"/>
    12                 <xs:element name="CustomerName" type="xs:string"/>
    13                 <xs:element name="OrderItems">
    14                     <xs:complexType>
    15                         <xs:sequence>
    16                             <xs:element name="Produdct" maxOccurs="unbounded">
    17                                 <xs:complexType>
    18                                     <xs:sequence>
    19                                         <xs:element name="ProductNo" type="xs:string"/>
    20                                         <xs:element name="ProductName" type="xs:string"/>
    21                                         <xs:element name="Price" type="xs:float"/>
    22                                         <xs:element name="Amount" type="xs:int"/>
    23                                     </xs:sequence>
    24                                 </xs:complexType>
    25                             </xs:element>
    26                         </xs:sequence>
    27                     </xs:complexType>
    28                 </xs:element>
    29             </xs:sequence>
    30         </xs:complexType>
    31     </xs:element>
    32 </xs:schema>
    Order.xsd

    上面是Order.xsd的内容

    2、根据XSD生成示例Xml

    在XSD文件上右击 -> Generate -> XmlFile

    会弹出一个框:

    Prefix这里,如果不需要,可以参考上图自行清空,如果一些可选节点也需要生成示例数据,上图中的Create optional attributes、Create optional elements这二项也勾选上。

    生成的order.xml内容如下:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!--Sample XML file generated by XMLSpy v2013 (http://www.altova.com)-->
     3 <Order xsi:noNamespaceSchemaLocation="order.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
     4     <OrderNo>0000001</OrderNo>
     5     <OrderDateTime>2001-12-17T09:30:47Z</OrderDateTime>
     6     <CustomerName>jimmy</CustomerName>
     7     <OrderItems>
     8         <Produdct>
     9             <ProductNo>P-01</ProductNo>
    10             <ProductName>Book</ProductName>
    11             <Price>1.14159E0</Price>
    12             <Amount>1</Amount>
    13         </Produdct>
    14         <Produdct>
    15             <ProductNo>P-02</ProductNo>
    16             <ProductName>iPhone 5C</ProductName>
    17             <Price>3.14159E0</Price>
    18             <Amount>2</Amount>
    19         </Produdct>
    20     </OrderItems>
    21 </Order>
    Order.xml

    3、根据xsd生成java类

    同样在xsd上右击 -> Generate -> JAXB Classes... 剩下的事情,大家都知道了

      1 //
      2 // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
      3 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
      4 // Any modifications to this file will be lost upon recompilation of the source schema. 
      5 // Generated on: 2014.01.24 at 11:09:15 ���� CST 
      6 //
      7 
      8 
      9 package model;
     10 
     11 import java.util.ArrayList;
     12 import java.util.List;
     13 import javax.xml.bind.annotation.XmlAccessType;
     14 import javax.xml.bind.annotation.XmlAccessorType;
     15 import javax.xml.bind.annotation.XmlElement;
     16 import javax.xml.bind.annotation.XmlRootElement;
     17 import javax.xml.bind.annotation.XmlSchemaType;
     18 import javax.xml.bind.annotation.XmlType;
     19 import javax.xml.datatype.XMLGregorianCalendar;
     20 
     21 
     22 /**
     23  * <p>Java class for anonymous complex type.
     24  * 
     25  * <p>The following schema fragment specifies the expected content contained within this class.
     26  * 
     27  * <pre>
     28  * &lt;complexType>
     29  *   &lt;complexContent>
     30  *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     31  *       &lt;sequence>
     32  *         &lt;element name="OrderNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
     33  *         &lt;element name="OrderDateTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
     34  *         &lt;element name="CustomerName" type="{http://www.w3.org/2001/XMLSchema}string"/>
     35  *         &lt;element name="OrderItems">
     36  *           &lt;complexType>
     37  *             &lt;complexContent>
     38  *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     39  *                 &lt;sequence>
     40  *                   &lt;element name="Produdct" maxOccurs="unbounded">
     41  *                     &lt;complexType>
     42  *                       &lt;complexContent>
     43  *                         &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     44  *                           &lt;sequence>
     45  *                             &lt;element name="ProductNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
     46  *                             &lt;element name="ProductName" type="{http://www.w3.org/2001/XMLSchema}string"/>
     47  *                             &lt;element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
     48  *                             &lt;element name="Amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
     49  *                           &lt;/sequence>
     50  *                         &lt;/restriction>
     51  *                       &lt;/complexContent>
     52  *                     &lt;/complexType>
     53  *                   &lt;/element>
     54  *                 &lt;/sequence>
     55  *               &lt;/restriction>
     56  *             &lt;/complexContent>
     57  *           &lt;/complexType>
     58  *         &lt;/element>
     59  *       &lt;/sequence>
     60  *     &lt;/restriction>
     61  *   &lt;/complexContent>
     62  * &lt;/complexType>
     63  * </pre>
     64  * 
     65  * 
     66  */
     67 @XmlAccessorType(XmlAccessType.FIELD)
     68 @XmlType(name = "", propOrder = {
     69     "orderNo",
     70     "orderDateTime",
     71     "customerName",
     72     "orderItems"
     73 })
     74 @XmlRootElement(name = "Order")
     75 public class Order {
     76 
     77     @XmlElement(name = "OrderNo", required = true)
     78     protected String orderNo;
     79     @XmlElement(name = "OrderDateTime", required = true)
     80     @XmlSchemaType(name = "dateTime")
     81     protected XMLGregorianCalendar orderDateTime;
     82     @XmlElement(name = "CustomerName", required = true)
     83     protected String customerName;
     84     @XmlElement(name = "OrderItems", required = true)
     85     protected Order.OrderItems orderItems;
     86 
     87     /**
     88      * Gets the value of the orderNo property.
     89      * 
     90      * @return
     91      *     possible object is
     92      *     {@link String }
     93      *     
     94      */
     95     public String getOrderNo() {
     96         return orderNo;
     97     }
     98 
     99     /**
    100      * Sets the value of the orderNo property.
    101      * 
    102      * @param value
    103      *     allowed object is
    104      *     {@link String }
    105      *     
    106      */
    107     public void setOrderNo(String value) {
    108         this.orderNo = value;
    109     }
    110 
    111     /**
    112      * Gets the value of the orderDateTime property.
    113      * 
    114      * @return
    115      *     possible object is
    116      *     {@link XMLGregorianCalendar }
    117      *     
    118      */
    119     public XMLGregorianCalendar getOrderDateTime() {
    120         return orderDateTime;
    121     }
    122 
    123     /**
    124      * Sets the value of the orderDateTime property.
    125      * 
    126      * @param value
    127      *     allowed object is
    128      *     {@link XMLGregorianCalendar }
    129      *     
    130      */
    131     public void setOrderDateTime(XMLGregorianCalendar value) {
    132         this.orderDateTime = value;
    133     }
    134 
    135     /**
    136      * Gets the value of the customerName property.
    137      * 
    138      * @return
    139      *     possible object is
    140      *     {@link String }
    141      *     
    142      */
    143     public String getCustomerName() {
    144         return customerName;
    145     }
    146 
    147     /**
    148      * Sets the value of the customerName property.
    149      * 
    150      * @param value
    151      *     allowed object is
    152      *     {@link String }
    153      *     
    154      */
    155     public void setCustomerName(String value) {
    156         this.customerName = value;
    157     }
    158 
    159     /**
    160      * Gets the value of the orderItems property.
    161      * 
    162      * @return
    163      *     possible object is
    164      *     {@link Order.OrderItems }
    165      *     
    166      */
    167     public Order.OrderItems getOrderItems() {
    168         return orderItems;
    169     }
    170 
    171     /**
    172      * Sets the value of the orderItems property.
    173      * 
    174      * @param value
    175      *     allowed object is
    176      *     {@link Order.OrderItems }
    177      *     
    178      */
    179     public void setOrderItems(Order.OrderItems value) {
    180         this.orderItems = value;
    181     }
    182 
    183 
    184     /**
    185      * <p>Java class for anonymous complex type.
    186      * 
    187      * <p>The following schema fragment specifies the expected content contained within this class.
    188      * 
    189      * <pre>
    190      * &lt;complexType>
    191      *   &lt;complexContent>
    192      *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    193      *       &lt;sequence>
    194      *         &lt;element name="Produdct" maxOccurs="unbounded">
    195      *           &lt;complexType>
    196      *             &lt;complexContent>
    197      *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    198      *                 &lt;sequence>
    199      *                   &lt;element name="ProductNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
    200      *                   &lt;element name="ProductName" type="{http://www.w3.org/2001/XMLSchema}string"/>
    201      *                   &lt;element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
    202      *                   &lt;element name="Amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
    203      *                 &lt;/sequence>
    204      *               &lt;/restriction>
    205      *             &lt;/complexContent>
    206      *           &lt;/complexType>
    207      *         &lt;/element>
    208      *       &lt;/sequence>
    209      *     &lt;/restriction>
    210      *   &lt;/complexContent>
    211      * &lt;/complexType>
    212      * </pre>
    213      * 
    214      * 
    215      */
    216     @XmlAccessorType(XmlAccessType.FIELD)
    217     @XmlType(name = "", propOrder = {
    218         "produdct"
    219     })
    220     public static class OrderItems {
    221 
    222         @XmlElement(name = "Produdct", required = true)
    223         protected List<Order.OrderItems.Produdct> produdct;
    224 
    225         /**
    226          * Gets the value of the produdct property.
    227          * 
    228          * <p>
    229          * This accessor method returns a reference to the live list,
    230          * not a snapshot. Therefore any modification you make to the
    231          * returned list will be present inside the JAXB object.
    232          * This is why there is not a <CODE>set</CODE> method for the produdct property.
    233          * 
    234          * <p>
    235          * For example, to add a new item, do as follows:
    236          * <pre>
    237          *    getProdudct().add(newItem);
    238          * </pre>
    239          * 
    240          * 
    241          * <p>
    242          * Objects of the following type(s) are allowed in the list
    243          * {@link Order.OrderItems.Produdct }
    244          * 
    245          * 
    246          */
    247         public List<Order.OrderItems.Produdct> getProdudct() {
    248             if (produdct == null) {
    249                 produdct = new ArrayList<Order.OrderItems.Produdct>();
    250             }
    251             return this.produdct;
    252         }
    253 
    254 
    255         /**
    256          * <p>Java class for anonymous complex type.
    257          * 
    258          * <p>The following schema fragment specifies the expected content contained within this class.
    259          * 
    260          * <pre>
    261          * &lt;complexType>
    262          *   &lt;complexContent>
    263          *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    264          *       &lt;sequence>
    265          *         &lt;element name="ProductNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
    266          *         &lt;element name="ProductName" type="{http://www.w3.org/2001/XMLSchema}string"/>
    267          *         &lt;element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
    268          *         &lt;element name="Amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
    269          *       &lt;/sequence>
    270          *     &lt;/restriction>
    271          *   &lt;/complexContent>
    272          * &lt;/complexType>
    273          * </pre>
    274          * 
    275          * 
    276          */
    277         @XmlAccessorType(XmlAccessType.FIELD)
    278         @XmlType(name = "", propOrder = {
    279             "productNo",
    280             "productName",
    281             "price",
    282             "amount"
    283         })
    284         public static class Produdct {
    285 
    286             @XmlElement(name = "ProductNo", required = true)
    287             protected String productNo;
    288             @XmlElement(name = "ProductName", required = true)
    289             protected String productName;
    290             @XmlElement(name = "Price")
    291             protected float price;
    292             @XmlElement(name = "Amount")
    293             protected int amount;
    294 
    295             /**
    296              * Gets the value of the productNo property.
    297              * 
    298              * @return
    299              *     possible object is
    300              *     {@link String }
    301              *     
    302              */
    303             public String getProductNo() {
    304                 return productNo;
    305             }
    306 
    307             /**
    308              * Sets the value of the productNo property.
    309              * 
    310              * @param value
    311              *     allowed object is
    312              *     {@link String }
    313              *     
    314              */
    315             public void setProductNo(String value) {
    316                 this.productNo = value;
    317             }
    318 
    319             /**
    320              * Gets the value of the productName property.
    321              * 
    322              * @return
    323              *     possible object is
    324              *     {@link String }
    325              *     
    326              */
    327             public String getProductName() {
    328                 return productName;
    329             }
    330 
    331             /**
    332              * Sets the value of the productName property.
    333              * 
    334              * @param value
    335              *     allowed object is
    336              *     {@link String }
    337              *     
    338              */
    339             public void setProductName(String value) {
    340                 this.productName = value;
    341             }
    342 
    343             /**
    344              * Gets the value of the price property.
    345              * 
    346              */
    347             public float getPrice() {
    348                 return price;
    349             }
    350 
    351             /**
    352              * Sets the value of the price property.
    353              * 
    354              */
    355             public void setPrice(float value) {
    356                 this.price = value;
    357             }
    358 
    359             /**
    360              * Gets the value of the amount property.
    361              * 
    362              */
    363             public int getAmount() {
    364                 return amount;
    365             }
    366 
    367             /**
    368              * Sets the value of the amount property.
    369              * 
    370              */
    371             public void setAmount(int value) {
    372                 this.amount = value;
    373             }
    374 
    375         }
    376 
    377     }
    378 
    379 }
    order.java

    上面是根据刚才的order.xsd生成的order类,package名称是model(当然生成java class的时候,你可以根据实际情况,设成任何自己需要的package名)

    同时还会生成一个ObjectFactory类:

     1 //
     2 // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
     3 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
     4 // Any modifications to this file will be lost upon recompilation of the source schema. 
     5 // Generated on: 2014.01.24 at 11:09:15 ���� CST 
     6 //
     7 
     8 
     9 package model;
    10 
    11 import javax.xml.bind.annotation.XmlRegistry;
    12 
    13 
    14 /**
    15  * This object contains factory methods for each 
    16  * Java content interface and Java element interface 
    17  * generated in the model package. 
    18  * <p>An ObjectFactory allows you to programatically 
    19  * construct new instances of the Java representation 
    20  * for XML content. The Java representation of XML 
    21  * content can consist of schema derived interfaces 
    22  * and classes representing the binding of schema 
    23  * type definitions, element declarations and model 
    24  * groups.  Factory methods for each of these are 
    25  * provided in this class.
    26  * 
    27  */
    28 @XmlRegistry
    29 public class ObjectFactory {
    30 
    31 
    32     /**
    33      * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: model
    34      * 
    35      */
    36     public ObjectFactory() {
    37     }
    38 
    39     /**
    40      * Create an instance of {@link Order.OrderItems }
    41      * 
    42      */
    43     public Order.OrderItems createOrderOrderItems() {
    44         return new Order.OrderItems();
    45     }
    46 
    47     /**
    48      * Create an instance of {@link Order }
    49      * 
    50      */
    51     public Order createOrder() {
    52         return new Order();
    53     }
    54 
    55     /**
    56      * Create an instance of {@link Order.OrderItems.Produdct }
    57      * 
    58      */
    59     public Order.OrderItems.Produdct createOrderOrderItemsProdudct() {
    60         return new Order.OrderItems.Produdct();
    61     }
    62 
    63 }
    ObjectFactory.java

    4、Object <-> XML 的示例代码

     1     public void testXmlToObj() {
     2         JAXBContext jc;
     3         try {
     4             jc = JAXBContext.newInstance("model");
     5             Unmarshaller u = jc.createUnmarshaller();
     6             String xmlFilePath = AppTest.class.getResource("/").getPath()
     7                     + "order.xml";
     8             System.out.println(xmlFilePath);
     9             Order order = (Order) u.unmarshal(new File(xmlFilePath));
    10             assertTrue(order.getOrderNo().equals("0000001"));
    11             assertTrue(order.getCustomerName().equals("jimmy"));
    12             for (int i = 0; i < order.getOrderItems().getProdudct().size(); i++) {
    13                 System.out.println(getProductDesc(order.getOrderItems()
    14                         .getProdudct().get(i)));
    15             }
    16         } catch (Exception e) {
    17             e.printStackTrace();
    18         }
    19     }
    20 
    21     public void testObjToXml() {
    22         try {
    23             ObjectFactory of = new ObjectFactory();
    24             Order order = of.createOrder();
    25             Order.OrderItems orderItems = of.createOrderOrderItems();
    26             
    27             Order.OrderItems.Produdct product1 = new Order.OrderItems.Produdct();
    28             product1.setProductNo("A-01");
    29             product1.setProductName("Car");
    30             product1.setPrice(1000000);
    31             product1.setAmount(1);
    32             
    33             orderItems.getProdudct().add(product1);
    34             
    35             Order.OrderItems.Produdct product2 = new Order.OrderItems.Produdct();
    36             product2.setProductNo("B-01");
    37             product2.setProductName("Book");
    38             product2.setPrice(200);
    39             product2.setAmount(2);
    40             
    41             orderItems.getProdudct().add(product2);
    42         
    43             order.setOrderItems(orderItems);
    44 
    45             JAXBContext jc = JAXBContext.newInstance("model");
    46             Marshaller ms = jc.createMarshaller();
    47             ms.setProperty("jaxb.encoding", "UTF-8");
    48             ms.setProperty("jaxb.formatted.output", true);
    49             String xmlFilePath = AppTest.class.getResource("/").getPath()
    50                     + "order_new.xml";
    51             ms.marshal(order, new File(xmlFilePath));
    52             
    53             System.out.println("testObjToXml");
    54         } catch (Exception e) {
    55             e.printStackTrace();
    56 
    57         }
    58     }
    object xml

    示例源代码下载:jaxb-helloworld.zip (注:这是一个maven工程,命令行下直接mvn clean test,就可以测试)

  • 相关阅读:
    PHP开发学习门户改版效果图投票
    怎样用js得到当前页面的url信息方法(JS获取当前网址信息)
    java 获取当期时间之前几小时的时间
    超人学院Hadoop大数据技术资源分享
    plsql导入一个目录下全部excel
    UML简单介绍
    Mod in math
    父母之爱子,则为之计深远是什么意思?_百度知道
    2014创客118新年大爬梯_活动行-国内最好的活动报名及售票平台!
    北京创客空间 BEIJING MAXPACE的小站
  • 原文地址:https://www.cnblogs.com/yjmyzz/p/3532334.html
Copyright © 2020-2023  润新知