ITPub博客

首页 > IT职业 > IT职场 > java JAXB 学习笔记

java JAXB 学习笔记

IT职场 作者:llittle 时间:2021-09-09 09:12:10 0 删除 编辑

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 
 2 <!-- edited with XMLSpy v2013 (http://www.altova.com) by  () -->
 3 
 4     
 5         
 6             Comment describing your root element
 7         
 8         
 9             
10                 
11                 
12                 
13                 
14                     
15                         
16                             
17                                 
18                                     
19                                         
20                                         
21                                         
22                                         
23                                     
24                                 
25                             
26                         
27                     
28                 
29             
30         
31     
32 


上面是Order.xsd的内容

2、根据XSD生成示例Xml

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

图片描述

会弹出一个框:

图片描述

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

生成的order.xml内容如下:

 1 
 2 <!--Sample XML file generated by XMLSpy v2013 (http://www.altova.com)-->
 3 
 4     0000001
 5     2001-12-17T09:30:47Z
 6     jimmy
 7     
 8         
 9             P-01
10             Book
11             1.14159E0
12             1
13         
14         
15             P-02
16             iPhone 5C
17             3.14159E0
18             2
19         
20     
21 

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 http://java.sun.com/xml/jaxb 
  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  * 

Java class for anonymous complex type.  24  *   25  * 

The following schema fragment specifies the expected content contained within this class.  26  *   27  * 

 28  * <complexType>
 29  *   <complexContent>
 30  *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 31  *       <sequence>
 32  *         <element name="OrderNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
 33  *         <element name="OrderDateTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
 34  *         <element name="CustomerName" type="{http://www.w3.org/2001/XMLSchema}string"/>
 35  *         <element name="OrderItems">
 36  *           <complexType>
 37  *             <complexContent>
 38  *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 39  *                 <sequence>
 40  *                   <element name="Produdct" maxOccurs="unbounded">
 41  *                     <complexType>
 42  *                       <complexContent>
 43  *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 44  *                           <sequence>
 45  *                             <element name="ProductNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
 46  *                             <element name="ProductName" type="{http://www.w3.org/2001/XMLSchema}string"/>
 47  *                             <element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
 48  *                             <element name="Amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
 49  *                           </sequence>
 50  *                         </restriction>
 51  *                       </complexContent>
 52  *                     </complexType>
 53  *                   </element>
 54  *                 </sequence>
 55  *               </restriction>
 56  *             </complexContent>
 57  *           </complexType>
 58  *         </element>
 59  *       </sequence>
 60  *     </restriction>
 61  *   </complexContent>
 62  * </complexType>
 63  * 
 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      * 

Java class for anonymous complex type. 186      *  187      * 

The following schema fragment specifies the expected content contained within this class. 188      *  189      * 

190      * <complexType>
191      *   <complexContent>
192      *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
193      *       <sequence>
194      *         <element name="Produdct" maxOccurs="unbounded">
195      *           <complexType>
196      *             <complexContent>
197      *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
198      *                 <sequence>
199      *                   <element name="ProductNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
200      *                   <element name="ProductName" type="{http://www.w3.org/2001/XMLSchema}string"/>
201      *                   <element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
202      *                   <element name="Amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
203      *                 </sequence>
204      *               </restriction>
205      *             </complexContent>
206      *           </complexType>
207      *         </element>
208      *       </sequence>
209      *     </restriction>
210      *   </complexContent>
211      * </complexType>
212      * 
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 produdct; 224  225         /** 226          * Gets the value of the produdct property. 227          *  228          * 

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 set method for the produdct property. 233          *  234          * 

235          * For example, to add a new item, do as follows: 236          * 

237          *    getProdudct().add(newItem);
238          * 
239          *  240          *  241          * 

242          * Objects of the following type(s) are allowed in the list 243          * {@link Order.OrderItems.Produdct } 244          *  245          *  246          */ 247         public List getProdudct() { 248             if (produdct == null) { 249                 produdct = new ArrayList(); 250             } 251             return this.produdct; 252         } 253  254  255         /** 256          * 

Java class for anonymous complex type. 257          *  258          * 

The following schema fragment specifies the expected content contained within this class. 259          *  260          * 

261          * <complexType>
262          *   <complexContent>
263          *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
264          *       <sequence>
265          *         <element name="ProductNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
266          *         <element name="ProductName" type="{http://www.w3.org/2001/XMLSchema}string"/>
267          *         <element name="Price" type="{http://www.w3.org/2001/XMLSchema}float"/>
268          *         <element name="Amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
269          *       </sequence>
270          *     </restriction>
271          *   </complexContent>
272          * </complexType>
273          * 
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.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 http://java.sun.com/xml/jaxb 
 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  * 

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 }

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 



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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/813/viewspace-2800435/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-12

  • 博文量
    448
  • 访问量
    4369