JAXB教程

前端之家收集整理的这篇文章主要介绍了JAXB教程前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

简介

JAXB(Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术。该过程中,JAXB也提供了将XML实例文档反向生成Java对象树的方法,并能将Java对象树的内容重新写到 XML实例文档。
JAXB2.0是JDK 1.6的组成部分。我们不需要下载第三方jar包 即可做到轻松转换。

概念

Marshaller接口,将Java对象序列化为XML数据。
Unmarshaller接口,将XML数据反序列化为Java对象。

@XmlType,将Java类或枚举类型映射到XML模式类型
@XmlAccessorType(XmlAccessType.FIELD) ,控制字段或属性的序列化。FIELD表示JAXB将自动绑定Java类中的每个非静态的(static)、非瞬态的(由@XmlTransient标 注)字段到XML。其他值还有XmlAccessType.PROPERTY和XmlAccessType.NONE。
@XmlAccessorOrder,控制JAXB 绑定类中属性和字段的排序。
@XmlJavaTypeAdapter,使用定制的适配器(即扩展抽象类XmlAdapter并覆盖marshal()和unmarshal()方法),以序列化Java类为XML。
@XmlElementWrapper ,对于数组或集合(即包含多个元素的成员变量),生成一个包装该数组或集合的XML元素(称为包装器)。
@XmlRootElement,将Java类或枚举类型映射到XML元素。
@XmlElement,将Java类的一个属性映射到与属性同名的一个XML元素。
@XmlAttribute,将Java类的一个属性映射到与属性同名的一个XML属性

示例

Order.java

  1. package com.ricky.domain;
  2.  
  3. import javax.xml.bind.annotation.*;
  4. import java.util.List;
  5. import java.util.Set;
  6.  
  7. /** * 订单 * * @author Ricky Fung * @create 2016-06-13 18:27 */
  8. @XmlAccessorType(XmlAccessType.FIELD)
  9. @XmlRootElement
  10. @XmlType(propOrder = {"id","totalPrice","category","shoppingList","tags","address"})
  11. public class Order {
  12.  
  13. @XmlAttribute(name="id")
  14. private long id;
  15. private String category;
  16.  
  17. @XmlElementWrapper(name = "shopping_list")
  18. @XmlElement(name = "shopping_item")
  19. private List<ShoppingItem> shoppingList;
  20.  
  21. @XmlElementWrapper(name = "tags")
  22. @XmlElement(name = "tag")
  23. private Set<String> tags;
  24.  
  25. @XmlElement(name = "addr",required = true)
  26. private Address address;
  27.  
  28. @XmlElement(name = "total_price")
  29. private float totalPrice;
  30.  
  31. public long getId() {
  32. return id;
  33. }
  34.  
  35. public void setId(long id) {
  36. this.id = id;
  37. }
  38.  
  39. public String getCategory() {
  40. return category;
  41. }
  42.  
  43. public void setCategory(String category) {
  44. this.category = category;
  45. }
  46.  
  47. public List<ShoppingItem> getShoppingList() {
  48. return shoppingList;
  49. }
  50.  
  51. public void setShoppingList(List<ShoppingItem> shoppingList) {
  52. this.shoppingList = shoppingList;
  53. }
  54.  
  55. public Set<String> getTags() {
  56. return tags;
  57. }
  58.  
  59. public void setTags(Set<String> tags) {
  60. this.tags = tags;
  61. }
  62.  
  63. public Address getAddress() {
  64. return address;
  65. }
  66.  
  67. public void setAddress(Address address) {
  68. this.address = address;
  69. }
  70.  
  71. public float getTotalPrice() {
  72. return totalPrice;
  73. }
  74.  
  75. public void setTotalPrice(float totalPrice) {
  76. this.totalPrice = totalPrice;
  77. }
  78.  
  79. @Override
  80. public String toString() {
  81. return "Order{" +
  82. "id=" + id +
  83. ",category='" + category + '\'' +
  84. ",shoppingList=" + shoppingList +
  85. ",tags=" + tags +
  86. ",address=" + address +
  87. ",totalPrice=" + totalPrice +
  88. '}';
  89. }
  90. }

ShoppingItem.java

  1. package com.ricky.domain;
  2.  
  3. import javax.xml.bind.annotation.XmlAccessType;
  4. import javax.xml.bind.annotation.XmlAccessorType;
  5.  
  6. /** * 购物项 * * @author Ricky Fung * @create 2016-06-13 19:00 */
  7. @XmlAccessorType(XmlAccessType.FIELD)
  8. public class ShoppingItem {
  9. private String name;
  10. private float price;
  11. private int num;
  12.  
  13. public String getName() {
  14. return name;
  15. }
  16.  
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20.  
  21. public float getPrice() {
  22. return price;
  23. }
  24.  
  25. public void setPrice(float price) {
  26. this.price = price;
  27. }
  28.  
  29. public int getNum() {
  30. return num;
  31. }
  32.  
  33. public void setNum(int num) {
  34. this.num = num;
  35. }
  36.  
  37. @Override
  38. public String toString() {
  39. return "ShopItem{" +
  40. "name='" + name + '\'' +
  41. ",price=" + price +
  42. ",num=" + num +
  43. '}';
  44. }
  45. }

Address.java

  1. package com.ricky.domain;
  2.  
  3. import javax.xml.bind.annotation.XmlAccessType;
  4. import javax.xml.bind.annotation.XmlAccessorType;
  5.  
  6. /** * 收货地址 * * @author Ricky Fung * @create 2016-06-13 18:28 */
  7. @XmlAccessorType(XmlAccessType.FIELD)
  8. public class Address {
  9. private String province;
  10. private String city;
  11. private String district;
  12. private String street;
  13.  
  14. public String getProvince() {
  15. return province;
  16. }
  17.  
  18. public void setProvince(String province) {
  19. this.province = province;
  20. }
  21.  
  22. public String getCity() {
  23. return city;
  24. }
  25.  
  26. public void setCity(String city) {
  27. this.city = city;
  28. }
  29.  
  30. public String getDistrict() {
  31. return district;
  32. }
  33.  
  34. public void setDistrict(String district) {
  35. this.district = district;
  36. }
  37.  
  38. public String getStreet() {
  39. return street;
  40. }
  41.  
  42. public void setStreet(String street) {
  43. this.street = street;
  44. }
  45.  
  46. @Override
  47. public String toString() {
  48. return "Address{" +
  49. "province='" + province + '\'' +
  50. ",city='" + city + '\'' +
  51. ",district='" + district + '\'' +
  52. ",street='" + street + '\'' +
  53. '}';
  54. }
  55. }

JAXBDemo.java

  1. package com.ricky;
  2.  
  3. import com.ricky.domain.Address;
  4. import com.ricky.domain.Order;
  5. import com.ricky.domain.ShoppingItem;
  6. import com.ricky.util.JAXBUtil;
  7. import javax.xml.bind.JAXBException;
  8. import java.util.*;
  9.  
  10. /** * JAXB示例 * * @author Ricky Fung * @create 2016-06-13 18:15 */
  11. public class JAXBDemo {
  12.  
  13. public static void main(String[] args) throws JAXBException {
  14.  
  15. Order order = new Order();
  16. order.setId(2);
  17. order.setCategory("3C");
  18. Set<String> tags = new HashSet<String>();
  19. tags.add("3C");
  20. tags.add("手机");
  21. order.setTags(tags);
  22.  
  23. List<ShoppingItem> shopping_list = new ArrayList<ShoppingItem>();
  24. ShoppingItem shoppingItem1 = new ShoppingItem();
  25. shoppingItem1.setName("Apple 6s Plus 64G");
  26. shoppingItem1.setPrice(6499f);
  27. shoppingItem1.setNum(1);
  28. shopping_list.add(shoppingItem1);
  29.  
  30. ShoppingItem shoppingItem2 = new ShoppingItem();
  31. shoppingItem2.setName("魅蓝Note3 32G");
  32. shoppingItem2.setPrice(999f);
  33. shoppingItem2.setNum(1);
  34. shopping_list.add(shoppingItem2);
  35.  
  36. order.setShoppingList(shopping_list);
  37.  
  38. order.setTotalPrice(7498f);
  39.  
  40. Address address = new Address();
  41. address.setProvince("湖北省");
  42. address.setCity("武汉市");
  43. address.setDistrict("武昌区");
  44. address.setStreet("复兴路");
  45. order.setAddress(address);
  46.  
  47. String xml = JAXBUtil.beanToXml(order);
  48. System.out.println("marshaller order:"+xml);
  49.  
  50. Order o = JAXBUtil.xmlToBean(xml,Order.class);
  51. System.out.println("unmarshaller order:"+o);
  52. }
  53. }
  1. package com.ricky.util;
  2.  
  3. import javax.xml.bind.JAXBContext;
  4. import javax.xml.bind.JAXBException;
  5. import javax.xml.bind.Marshaller;
  6. import javax.xml.bind.Unmarshaller;
  7. import java.io.StringReader;
  8. import java.io.StringWriter;
  9.  
  10. /** * JAXB工具类 * * @author Ricky Fung * @create 2016-06-13 18:20 */
  11. public class JAXBUtil {
  12.  
  13. public static String beanToXml(Object obj) throws JAXBException {
  14.  
  15. JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
  16. Marshaller marshaller = jaxbContext.createMarshaller();
  17.  
  18. // 用来指定是否使用换行和缩排对已编组XML数据进行格式化的属性名称
  19. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
  20. marshaller.setProperty(Marshaller.JAXB_ENCODING,"UTF-8");
  21.  
  22. StringWriter writer = new StringWriter();
  23. marshaller.marshal(obj,writer);
  24. return writer.toString();
  25. }
  26.  
  27. public static <T> T xmlToBean(String xml,Class<T> cls) throws JAXBException {
  28.  
  29. JAXBContext context = JAXBContext.newInstance(cls);
  30. Unmarshaller unmarshaller = context.createUnmarshaller();
  31.  
  32. return (T) unmarshaller.unmarshal(new StringReader(xml));
  33. }
  34. }

忽略字段

使用@XmlTransient

  1. package com.ricky.domain;
  2.  
  3. import javax.xml.bind.annotation.*;
  4. import java.util.List;
  5.  
  6. /** * ${DESCRIPTION} * * @author Ricky Fung * @create 2016-06-14 18:35 */
  7. @XmlAccessorType(XmlAccessType.FIELD)
  8. @XmlRootElement
  9. public class Student {
  10. private long id;
  11. private String name;
  12.  
  13. @XmlTransient
  14. private int age;
  15.  
  16. @XmlElementWrapper(name = "hobbies")
  17. @XmlElement(name = "hobby")
  18. private List<String> hobbies;
  19.  
  20. public long getId() {
  21. return id;
  22. }
  23.  
  24. public void setId(long id) {
  25. this.id = id;
  26. }
  27.  
  28. public String getName() {
  29. return name;
  30. }
  31.  
  32. public void setName(String name) {
  33. this.name = name;
  34. }
  35.  
  36. public int getAge() {
  37. return age;
  38. }
  39.  
  40. public void setAge(int age) {
  41. this.age = age;
  42. }
  43.  
  44. public List<String> getHobbies() {
  45. return hobbies;
  46. }
  47.  
  48. public void setHobbies(List<String> hobbies) {
  49. this.hobbies = hobbies;
  50. }
  51. }
  1. package com.ricky;
  2.  
  3. import com.ricky.domain.Student;
  4. import com.ricky.util.JAXBUtil;
  5. import javax.xml.bind.JAXBException;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. /** * ${DESCRIPTION} * * @author Ricky Fung * @create 2016-06-14 18:34 */
  10. public class JAXBExcludeDemo {
  11.  
  12. public static void main(String[] args) throws JAXBException {
  13.  
  14. Student student = new Student();
  15. student.setId(1l);
  16. student.setName("Ricky");
  17. student.setAge(27);
  18.  
  19. List<String> hobbies = new ArrayList<String>();
  20. hobbies.add("NBA");
  21. hobbies.add("电影");
  22. student.setHobbies(hobbies);
  23.  
  24. String xml = JAXBUtil.beanToXml(student);
  25. System.out.println(xml);
  26. }
  27. }

参考资料:
https://java.net/projects/jaxb2-commons/pages/Home

猜你在找的XML相关文章