JAXB注解使用,从xml文件生成xsd,在生成java类文件
JAXB命名空间及命名空间前缀处理
package-info.java
1 /** 2 * @author wangyunpeng 3 * 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.QUALIFIED 11 ) 12 package tlz.module.sem.model.gmc;
一.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) @XmlRootElement public class Address {}
4.@XmlAttribute
@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<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); }
三.示例
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 class Shop { 18 19 @XmlAttribute 20 privateString name; 21 22 // @XmlElement 23 privateString number; 24 25 @XmlElement 26 privateString describer; 27 28 @XmlElementWrapper(name ="orders") 29 @XmlElement(name ="order") 30 privateSet<Order> orders; 31 32 @XmlElement 33 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 @XmlRootElement 14 public class Order { 15 16 // @XmlElement 17 privateString shopName; 18 19 @XmlAttribute 20 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,int amount) { 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 @XmlType 10 @XmlAccessorType(XmlAccessType.FIELD) 11 @XmlRootElement 12 public class Customer { 13 14 @XmlAttribute 15 privateString name; 16 17 privateString gender; 18 19 privateString phoneNo; 20 21 privateAddress address; 22 23 privateSet<Order> orders; 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 @XmlRootElement 14 public class Address { 15 16 @XmlAttribute 17 privateString state; 18 19 @XmlElement 20 privateString province; 21 22 @XmlElement 23 privateString city; 24 25 @XmlElement 26 privateString street; 27 28 @XmlElement 29 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<String, Date> { 7 8 private String pattern = "yyyy-MM-dd HH:mm:ss"; 9 SimpleDateFormat fmt =new SimpleDateFormat(pattern); 10 11 @Override 12 publicDate unmarshal(String dateStr) throwsException { 13 return fmt.parse(dateStr); 14 } 15 16 @Override 17 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 class ShopTest { 15 16 publicstatic void main(String[] args) throws JAXBException, IOException{ 17 Set<Order> orders =new HashSet<Order>(); 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<Order> 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 <?xml version="1.0"encoding="UTF-8"standalone="yes"?> 2 <CHMart name="CHMart"> 3 <number>100000</number> 4 <describer>EveryThing</describer> 5 <address state="China"> 6 <province>ZheJiang</province> 7 <city>HangZhou</city> 8 <street>XiHuRoad</street> 9 <zip>310000</zip> 10 </address> 11 <orders> 12 <order orderNumber="LH59800"> 13 <shopName>Mart</shopName> 14 <price>80</price> 15 <amount>1</amount> 16 <purDate>2012-03-2512:57:23</purDate> 17 <customer name="David"> 18 <gender>male</gender> 19 <phoneNo>13699991000</phoneNo> 20 <address state="China"> 21 <province>JiangSu</province> 22 <city>NanJing</city> 23 <street>ZhongYangLu</street> 24 <zip>210000</zip> 25 </address> 26 </customer> 27 </order> 28 <order orderNumber="LH59900"> 29 <shopName>Mart</shopName> 30 <price>60</price> 31 <amount>1</amount> 32 <purDate>2012-03-2512:57:23</purDate> 33 <customer name="Jim"> 34 <gender>male</gender> 35 <phoneNo>13699990000</phoneNo> 36 <address state="China"> 37 <province>ShangHai</province> 38 <city>ShangHai</city> 39 <street>Huang</street> 40 <zip>200000</zip> 41 </address> 42 </customer> 43 </order> 44 </orders> 45 </CHMart>
以上是以一个简单的商店订单模型作为示例。
转自:http://blog.csdn.net/czplplp_900725/article/details/7888896
使用jaxb用xsd生成java类
jdk提供了xjc工具可以使xsd自动生成相应的java bean,这大大提高了开发的效率。同时,我们也可以使用trang.jar把xml轻松转化为xsd。下面是使用的举例。
第一步:准备book.xml文件
<Books> <Book> <name>书名A</name> <author>作者A</author> <price>作者A</price> </Book> <Book> <name>书名B</name> <author>作者B</author> <price>作者B</price> </Book> </Books>
第二步:使用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 // 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 4 // 在重新编译源模式时, 对此文件的所有修改都将丢失。 5 // 生成时间: 2020.09.22 时间 04:04:23 PM CST 6 // 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 * <p>anonymous complex type的 Java 类。 24 * 25 * <p>以下模式片段指定包含在此类中的预期内容。 26 * 27 * <pre> 28 * <complexType> 29 * <complexContent> 30 * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> 31 * <attribute name="u_avatar" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> 32 * <attribute name="u_email" use="required" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" /> 33 * <attribute name="u_hometown" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> 34 * <attribute name="u_id" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" /> 35 * <attribute name="u_job" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> 36 * <attribute name="u_mobile" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" /> 37 * <attribute name="u_mood" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> 38 * <attribute name="u_name" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> 39 * <attribute name="u_state" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> 40 * </restriction> 41 * </complexContent> 42 * </complexType> 43 * </pre> 44 * 45 * 46 */ 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 * @return 88 * possible object is 89 * {@link String } 90 * 91 */ 92 public String getUAvatar() { 93 return uAvatar; 94 } 95 96 /** 97 * 设置uAvatar属性的值。 98 * 99 * @param value 100 * allowed object is 101 * {@link String } 102 * 103 */ 104 public void setUAvatar(String value) { 105 this.uAvatar = value; 106 } 107 108 /** 109 * 获取uEmail属性的值。 110 * 111 * @return 112 * possible object is 113 * {@link String } 114 * 115 */ 116 public String getUEmail() { 117 return uEmail; 118 } 119 120 /** 121 * 设置uEmail属性的值。 122 * 123 * @param value 124 * allowed object is 125 * {@link String } 126 * 127 */ 128 public void setUEmail(String value) { 129 this.uEmail = value; 130 } 131 132 /** 133 * 获取uHometown属性的值。 134 * 135 * @return 136 * possible object is 137 * {@link String } 138 * 139 */ 140 public String getUHometown() { 141 return uHometown; 142 } 143 144 /** 145 * 设置uHometown属性的值。 146 * 147 * @param value 148 * allowed object is 149 * {@link String } 150 * 151 */ 152 public void setUHometown(String value) { 153 this.uHometown = value; 154 } 155 156 /** 157 * 获取uId属性的值。 158 * 159 * @return 160 * possible object is 161 * {@link BigInteger } 162 * 163 */ 164 public BigInteger getUId() { 165 return uId; 166 } 167 168 /** 169 * 设置uId属性的值。 170 * 171 * @param value 172 * allowed object is 173 * {@link BigInteger } 174 * 175 */ 176 public void setUId(BigInteger value) { 177 this.uId = value; 178 } 179 180 /** 181 * 获取uJob属性的值。 182 * 183 * @return 184 * possible object is 185 * {@link String } 186 * 187 */ 188 public String getUJob() { 189 return uJob; 190 } 191 192 /** 193 * 设置uJob属性的值。 194 * 195 * @param value 196 * allowed object is 197 * {@link String } 198 * 199 */ 200 public void setUJob(String value) { 201 this.uJob = value; 202 } 203 204 /** 205 * 获取uMobile属性的值。 206 * 207 * @return 208 * possible object is 209 * {@link BigInteger } 210 * 211 */ 212 public BigInteger getUMobile() { 213 return uMobile; 214 } 215 216 /** 217 * 设置uMobile属性的值。 218 * 219 * @param value 220 * allowed object is 221 * {@link BigInteger } 222 * 223 */ 224 public void setUMobile(BigInteger value) { 225 this.uMobile = value; 226 } 227 228 /** 229 * 获取uMood属性的值。 230 * 231 * @return 232 * possible object is 233 * {@link String } 234 * 235 */ 236 public String getUMood() { 237 return uMood; 238 } 239 240 /** 241 * 设置uMood属性的值。 242 * 243 * @param value 244 * allowed object is 245 * {@link String } 246 * 247 */ 248 public void setUMood(String value) { 249 this.uMood = value; 250 } 251 252 /** 253 * 获取uName属性的值。 254 * 255 * @return 256 * possible object is 257 * {@link String } 258 * 259 */ 260 public String getUName() { 261 return uName; 262 } 263 264 /** 265 * 设置uName属性的值。 266 * 267 * @param value 268 * allowed object is 269 * {@link String } 270 * 271 */ 272 public void setUName(String value) { 273 this.uName = value; 274 } 275 276 /** 277 * 获取uState属性的值。 278 * 279 * @return 280 * possible object is 281 * {@link String } 282 * 283 */ 284 public String getUState() { 285 return uState; 286 } 287 288 /** 289 * 设置uState属性的值。 290 * 291 * @param value 292 * allowed object is 293 * {@link String } 294 * 295 */ 296 public void setUState(String value) { 297 this.uState = value; 298 } 299 300 }