package-info.java
1 /**2 * @author wangyunpeng3 *4 */
5 @javax.xml.bind.annotation.XmlSchema(6 //生成xml文件的时候需要使用xmlns
7 xmlns = { @javax.xml.bind.annotation.XmlNs(prefix = "g", namespaceURI = "http://base.google.com/ns/1.0") }8 //读取xml文件的时候需要使用namespace和elementFormDefault
9 , namespace = "http://base.google.com/ns/1.0"
10 , elementFormDefault =javax.xml.bind.annotation.XmlNsForm.QUALIFIED11 )12 package tlz.module.sem.model.gmc;
package-info.java
一.Jaxb处理java对象和xml之间转换常用的annotation有:
@XmlType
@XmlElement
@XmlRootElement
@XmlAttribute
@XmlAccessorType
@XmlAccessorOrder
@XmlTransient
@XmlJavaTypeAdapter
二.常用annotation使用说明
1.XmlType
@XmlType用在class类的注解,常与@XmlRootElement,@XmlAccessorType一起使用。它有三个属性:name、propOrder、namespace,经常使用的只有前两个属性。如:
@XmlType(name = "basicStruct", propOrder ={"intValue","stringArray","stringValue")
在使用@XmlType的propOrder 属性时,必须列出JavaBean对象中的所有属性,否则会报错。
2.@XmlElement
@XmlElement将java对象的属性映射为xml的节点,在使用@XmlElement时,可通过name属性改变java对象属性在xml中显示的名称。如:
@XmlElement(name="Address")private String yourAddress;
3.@XmlRootElement
@XmlRootElement用于类级别的注解,对应xml的跟元素,常与 @XmlType 和 @XmlAccessorType一起使用。如:
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElementpublic class Address {}
4.@XmlAttribute
@XmlAttribute用于把java对象的属性映射为xml的属性,并可通过name属性为生成的xml属性指定别名。如:
@XmlAttribute(name="Country")private String state;
5.@XmlAccessorType
@XmlAccessorType用于指定由java对象生成xml文件时对java对象属性的访问方式。常与@XmlRootElement、@XmlType一起使用。它的属性值是XmlAccessType的4个枚举值,分 别为:
XmlAccessType.FIELD:java对象中的所有成员变量
XmlAccessType.PROPERTY:java对象中所有通过getter/setter方式访问的成员变量
XmlAccessType.PUBLIC_MEMBER:java对象中所有的public访问权限的成员变量和通过getter/setter方式访问的成员变量
XmlAccessType.NONE:java对象的所有属性都不映射为xml的元素
注意:@XmlAccessorType的默认访问级别是XmlAccessType.PUBLIC_MEMBER,因此,如果java对象中的private成员变量设置了public权限的getter/setter方法,就不要在private变量上使用@XmlElement和@XmlAttribute注解,否则在由java对象生成xml时会报同一个属性在java类里存在两次的错误。同理,如果@XmlAccessorType的访问权限为XmlAccessType.NONE,如果在java的成员变量上使用了@XmlElement或@XmlAttribute注解,这些成员变量依然可以映射到xml文件。
6.@XmlAccessorOrder
@XmlAccessorOrder用于对java对象生成的xml元素进行排序。它有两个属性值:
AccessorOrder.ALPHABETICAL:对生成的xml元素按字母书序排序
XmlAccessOrder.UNDEFINED:不排序
7.@XmlTransient
@XmlTransient用于标示在由java对象映射xml时,忽略此属性。即,在生成的xml文件中不出现此元素。
8.@XmlJavaTypeAdapter
@XmlJavaTypeAdapter常用在转换比较复杂的对象时,如map类型或者格式化日期等。使用此注解时,需要自己写一个adapter类继承XmlAdapter抽象类,并实现里面的方法。
@XmlJavaTypeAdapter(value=xxx.class),value为自己定义的adapter类
XmlAdapter如下:
public abstract class XmlAdapter{//Do-nothing constructor for the derived classes.
protectedXmlAdapter() {}//Convert a value type to a bound type.
public abstractBoundType unmarshal(ValueType v);//Convert a bound type to a value type.
public abstractValueType marshal(BoundType v);
}
三.示例
1.Shop.java
1 import java.util.Set;2
3 import javax.xml.bind.annotation.XmlAccessOrder;4 import javax.xml.bind.annotation.XmlAccessType;5 import javax.xml.bind.annotation.XmlAccessorType;6 import javax.xml.bind.annotation.XmlAttribute;7 import javax.xml.bind.annotation.XmlElement;8 import javax.xml.bind.annotation.XmlRootElement;9 import javax.xml.bind.annotation.XmlType;10 import javax.xml.bind.annotation.XmlElementWrapper;11 import javax.xml.bind.annotation.XmlAccessorOrder;12
13 @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)14 @XmlAccessorType(XmlAccessType.FIELD)15 @XmlType(name ="shop", propOrder = {"name", "number","describer", "address","orders"})16 @XmlRootElement(name ="CHMart")17 public classShop {18
19 @XmlAttribute20 privateString name;21
22 //@XmlElement
23 privateString number;24
25 @XmlElement26 privateString describer;27
28 @XmlElementWrapper(name ="orders")29 @XmlElement(name ="order")30 privateSetorders;31
32 @XmlElement33 privateAddress address;34
35 publicShop() {36 }37
38 publicShop(String name, String number, String describer, Address address) {39 this.name =name;40 this.number =number;41 this.describer =describer;42 this.address =address;43 }44
45 getter/setter略46 }
备注:同时使用了@XmlType(propOrder={})和 @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL),但是生成的xml只按照propOrder定义的顺序生成元
2.Order.java
1 import java.math.BigDecimal;2 import java.util.Date;3
4 import javax.xml.bind.annotation.XmlAccessType;5 import javax.xml.bind.annotation.XmlAccessorType;6 import javax.xml.bind.annotation.XmlAttribute;7 import javax.xml.bind.annotation.XmlRootElement;8 import javax.xml.bind.annotation.XmlType;9 import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;10
11 @XmlType(name="order",propOrder={"shopName","orderNumber","price","amount","purDate","customer"})12 @XmlAccessorType(XmlAccessType.FIELD)13 @XmlRootElement14 public classOrder {15
16 //@XmlElement
17 privateString shopName;18
19 @XmlAttribute20 privateString orderNumber;21
22 //@XmlElement
23 @XmlJavaTypeAdapter(value=DateAdapter.class)24 privateDate purDate;25
26 //@XmlElement
27 privateBigDecimal price;28
29 //@XmlElement
30 privateint amount;31
32 //@XmlElement
33 privateCustomer customer;34
35 publicOrder() {36 }37
38 publicOrder(String shopName, String orderNumber, Date purDate,39 BigDecimal price,intamount) {40 this.shopName =shopName;41 this.orderNumber =orderNumber;42 this.purDate =purDate;43 this.price =price;44 this.amount =amount;45 }46
47 getter/setter略48 }
备注:@XmlAccessorType(XmlAccessType.FIELD),所以此处注释掉了@XmlElement,xml中依然会生成这些元素
3.Customer.java
1 import java.util.Set;2 import javax.xml.bind.annotation.XmlType;3 import javax.xml.bind.annotation.XmlAttribute;4 import javax.xml.bind.annotation.XmlElement;5 import javax.xml.bind.annotation.XmlRootElement;6 import javax.xml.bind.annotation.XmlAccessType;7 import javax.xml.bind.annotation.XmlAccessorType;8
9 @XmlType10 @XmlAccessorType(XmlAccessType.FIELD)11 @XmlRootElement12 public classCustomer {13
14 @XmlAttribute15 privateString name;16
17 privateString gender;18
19 privateString phoneNo;20
21 privateAddress address;22
23 privateSetorders;24
25 publicCustomer() {26 }27
28 publicCustomer(String name, String gender, String phoneNo, Address address) {29 this.name =name;30 this.gender =gender;31 this.phoneNo =phoneNo;32 this.address =address;33 }34
35 getter/setter略36 }
4.Address.java
1 import javax.xml.bind.annotation.XmlAttribute;2 import javax.xml.bind.annotation.XmlType;3 import javax.xml.bind.annotation.XmlElement;4 import javax.xml.bind.annotation.XmlRootElement;5 import javax.xml.bind.annotation.XmlAccessType;6 import javax.xml.bind.annotation.XmlAccessorType;7 import javax.xml.bind.annotation.XmlAccessOrder;8 import javax.xml.bind.annotation.XmlAccessorOrder;9
10 @XmlType(propOrder={"state","province","city","street","zip"})11 @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)12 @XmlAccessorType(XmlAccessType.NONE)13 @XmlRootElement14 public classAddress {15
16 @XmlAttribute17 privateString state;18
19 @XmlElement20 privateString province;21
22 @XmlElement23 privateString city;24
25 @XmlElement26 privateString street;27
28 @XmlElement29 privateString zip;30
31 publicAddress() {32 super();33 }34
35 publicAddress(String state, String province, String city, String street,36 String zip) {37 super();38 this.state =state;39 this.province =province;40 this.city =city;41 this.street =street;42 this.zip =zip;43 }44
45 getter/setter略46 }
备注:虽然@XmlAccessorType为XmlAccessType.NONE,但是在java类的私有属性上加了@XmlAttribute和@XmlElement注解后,这些私有成员会映射生成xml的元素
5.DateAdapter.java
1 import java.util.Date;2 import java.text.SimpleDateFormat;3
4 import javax.xml.bind.annotation.adapters.XmlAdapter;5
6 public class DateAdapter extendsXmlAdapter{7
8 private String pattern = "yyyy-MM-dd HH:mm:ss";9 SimpleDateFormat fmt =newSimpleDateFormat(pattern);10
11 @Override12 publicDate unmarshal(String dateStr) throwsException {13 return fmt.parse(dateStr);14 }15
16 @Override17 publicString marshal(Date date) throwsException {18 return fmt.format(date);19 }20
21 }
备注:用于格式化日期在xml中的显示格式,并且由xml unmarshal为java对象时,将字符串解析为Date对象
6.ShopTest.java
1 import java.io.FileReader;2 import java.io.FileWriter;3 import java.io.IOException;4 import java.math.BigDecimal;5 import java.util.Date;6 import java.util.HashSet;7 import java.util.Set;8
9 import javax.xml.bind.JAXBContext;10 import javax.xml.bind.JAXBException;11 import javax.xml.bind.Marshaller;12 import javax.xml.bind.Unmarshaller;13
14 public classShopTest {15
16 publicstatic voidmain(String[] args) throws JAXBException, IOException{17 Set orders =new HashSet();18
19 Address address1 =new Address("China","ShangHai", "ShangHai", "Huang","200000");20 Customer customer1 =new Customer("Jim","male", "13699990000", address1);21 Order order1 =new Order("Mart","LH59900", new Date(), newBigDecimal(60),1);22 order1.setCustomer(customer1);23
24 Address address2 =new Address("China","JiangSu", "NanJing", "ZhongYangLu","210000");25 Customer customer2 =new Customer("David","male", "13699991000", address2);26 Order order2 =new Order("Mart","LH59800", new Date(), newBigDecimal(80),1);27 order2.setCustomer(customer2);28
29 orders.add(order1);30 orders.add(order2);31
32 Address address3 =new Address("China","ZheJiang", "HangZhou", "XiHuRoad","310000");33 Shop shop =new Shop("CHMart","100000", "EveryThing",address3);34 shop.setOrder(orders);35
36
37 FileWriter writer =null;38 JAXBContext context = JAXBContext.newInstance(Shop.class);39 try{40 Marshaller marshal =context.createMarshaller();41 marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);42 marshal.marshal(shop, System.out);43
44 writer =new FileWriter("shop.xml");45 marshal.marshal(shop, writer);46 }catch(Exception e) {47 e.printStackTrace();48 }49
50 Unmarshaller unmarshal =context.createUnmarshaller();51 FileReader reader =new FileReader("shop.xml") ;52 Shop shop1 =(Shop)unmarshal.unmarshal(reader);53
54 Set orders1 =shop1.getOrder();55 for(Order order : orders1){56 System.out.println("***************************");57 System.out.println(order.getOrderNumber());58 System.out.println(order.getCustomer().getName());59 System.out.println("***************************");60 }61 }62 }
7.生成的xml文件
1
2
3 100000
4 EveryThing
5
6 ZheJiang
7 HangZhou
8 XiHuRoad
9 310000
10
11
12
13 Mart
14 80
15 1
16 2012-03-2512:57:23
17
18 male
19 13699991000
20
21 JiangSu
22 NanJing
23 ZhongYangLu
24 210000
25
26
27
28
29 Mart
30 60
31 1
32 2012-03-2512:57:23
33
34 male
35 13699990000
36
37 ShangHai
38 ShangHai
39 Huang
40 200000
41
42
43
44
45
以上是以一个简单的商店订单模型作为示例。
jdk提供了xjc工具可以使xsd自动生成相应的java bean,这大大提高了开发的效率。同时,我们也可以使用trang.jar把xml轻松转化为xsd。下面是使用的举例。
第一步:准备book.xml文件
书名A
作者A
作者A
书名B
作者B
作者B
第二步:使用trang.jar转化为xsd文件。在命令行执行:
java -jar D:\lib\trang.jar book.xml book.xsd
第三步:通过xsd文件,生成java类文件
现在可以使用jdk自带的xjc命令来生成代码了,xjc的具体使用方面就不多说,大家可以自己看看它的帮助文档
xjc book.xsd
xjc -p 包的路径 xsd的名字.xsd -d 目标的文件夹
xjc -p tb.module D:\FEED_BAK_DIR\user.xsd -d D:\FEED_BAK_DIR
生成出来的java类
1 //
2 //此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.8-b130911.1802 生成的3 //请访问 http://java.sun.com/xml/jaxb4 //在重新编译源模式时, 对此文件的所有修改都将丢失。5 //生成时间: 2020.09.22 时间 04:04:23 PM CST6 //7
8
9 package tb.module;10
11 import java.math.BigInteger;12 import javax.xml.bind.annotation.XmlAccessType;13 import javax.xml.bind.annotation.XmlAccessorType;14 import javax.xml.bind.annotation.XmlAttribute;15 import javax.xml.bind.annotation.XmlRootElement;16 import javax.xml.bind.annotation.XmlSchemaType;17 import javax.xml.bind.annotation.XmlType;18 import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;19 import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;20
21
22 /**23 *
anonymous complex type的 Java 类。24 *25 *
以下模式片段指定包含在此类中的预期内容。26 *27 *
28 *44 *45 *46 */29 * 43 *30 * 42 *31 * 41 *32 * 33 * 34 * 35 * 36 * 37 * 38 * 39 * 40 *
47 @XmlAccessorType(XmlAccessType.FIELD)48 @XmlType(name = "")49 @XmlRootElement(name = "User")50 public class User {51
52 @XmlAttribute(name = "u_avatar", required = true)53 @XmlJavaTypeAdapter(CollapsedStringAdapter.class)54 @XmlSchemaType(name = "NCName")55 protected String uAvatar;56 @XmlAttribute(name = "u_email", required = true)57 @XmlSchemaType(name = "anySimpleType")58 protected String uEmail;59 @XmlAttribute(name = "u_hometown", required = true)60 @XmlJavaTypeAdapter(CollapsedStringAdapter.class)61 @XmlSchemaType(name = "NCName")62 protected String uHometown;63 @XmlAttribute(name = "u_id", required = true)64 protected BigInteger uId;65 @XmlAttribute(name = "u_job", required = true)66 @XmlJavaTypeAdapter(CollapsedStringAdapter.class)67 @XmlSchemaType(name = "NCName")68 protected String uJob;69 @XmlAttribute(name = "u_mobile", required = true)70 protected BigInteger uMobile;71 @XmlAttribute(name = "u_mood", required = true)72 @XmlJavaTypeAdapter(CollapsedStringAdapter.class)73 @XmlSchemaType(name = "NCName")74 protected String uMood;75 @XmlAttribute(name = "u_name", required = true)76 @XmlJavaTypeAdapter(CollapsedStringAdapter.class)77 @XmlSchemaType(name = "NCName")78 protected String uName;79 @XmlAttribute(name = "u_state", required = true)80 @XmlJavaTypeAdapter(CollapsedStringAdapter.class)81 @XmlSchemaType(name = "NCName")82 protected String uState;83
84 /**85 * 获取uAvatar属性的值。86 *87 * @return88 * possible object is89 * {@link String }90 *91 */
92 public String getUAvatar() {93 return uAvatar;94 }95
96 /**97 * 设置uAvatar属性的值。98 *99 * @param value100 * allowed object is101 * {@link String }102 *103 */
104 public void setUAvatar(String value) {105 this.uAvatar =value;106 }107
108 /**109 * 获取uEmail属性的值。110 *111 * @return112 * possible object is113 * {@link String }114 *115 */
116 public String getUEmail() {117 return uEmail;118 }119
120 /**121 * 设置uEmail属性的值。122 *123 * @param value124 * allowed object is125 * {@link String }126 *127 */
128 public void setUEmail(String value) {129 this.uEmail =value;130 }131
132 /**133 * 获取uHometown属性的值。134 *135 * @return136 * possible object is137 * {@link String }138 *139 */
140 public String getUHometown() {141 return uHometown;142 }143
144 /**145 * 设置uHometown属性的值。146 *147 * @param value148 * allowed object is149 * {@link String }150 *151 */
152 public void setUHometown(String value) {153 this.uHometown =value;154 }155
156 /**157 * 获取uId属性的值。158 *159 * @return160 * possible object is161 * {@link BigInteger }162 *163 */
164 public BigInteger getUId() {165 return uId;166 }167
168 /**169 * 设置uId属性的值。170 *171 * @param value172 * allowed object is173 * {@link BigInteger }174 *175 */
176 public void setUId(BigInteger value) {177 this.uId =value;178 }179
180 /**181 * 获取uJob属性的值。182 *183 * @return184 * possible object is185 * {@link String }186 *187 */
188 public String getUJob() {189 return uJob;190 }191
192 /**193 * 设置uJob属性的值。194 *195 * @param value196 * allowed object is197 * {@link String }198 *199 */
200 public void setUJob(String value) {201 this.uJob =value;202 }203
204 /**205 * 获取uMobile属性的值。206 *207 * @return208 * possible object is209 * {@link BigInteger }210 *211 */
212 public BigInteger getUMobile() {213 return uMobile;214 }215
216 /**217 * 设置uMobile属性的值。218 *219 * @param value220 * allowed object is221 * {@link BigInteger }222 *223 */
224 public void setUMobile(BigInteger value) {225 this.uMobile =value;226 }227
228 /**229 * 获取uMood属性的值。230 *231 * @return232 * possible object is233 * {@link String }234 *235 */
236 public String getUMood() {237 return uMood;238 }239
240 /**241 * 设置uMood属性的值。242 *243 * @param value244 * allowed object is245 * {@link String }246 *247 */
248 public void setUMood(String value) {249 this.uMood =value;250 }251
252 /**253 * 获取uName属性的值。254 *255 * @return256 * possible object is257 * {@link String }258 *259 */
260 public String getUName() {261 return uName;262 }263
264 /**265 * 设置uName属性的值。266 *267 * @param value268 * allowed object is269 * {@link String }270 *271 */
272 public void setUName(String value) {273 this.uName =value;274 }275
276 /**277 * 获取uState属性的值。278 *279 * @return280 * possible object is281 * {@link String }282 *283 */
284 public String getUState() {285 return uState;286 }287
288 /**289 * 设置uState属性的值。290 *291 * @param value292 * allowed object is293 * {@link String }294 *295 */
296 public void setUState(String value) {297 this.uState =value;298 }299
300 }
User.java