在我们的实际应用中,Xml中的结构往往不止这么简单,一般都会有2,3层。也就是说如果映射成对象就是聚合(组合)的情况 。

就用我们上一章的例子继续来讲,简单我们的Book的author现在不止是一个String类型的名子,他是一个对象Author,并包含作者的相关个人信息。那我们怎么做列?

直接看代码

  1. package com.jaxb.first;
  2. import javax.xml.bind.annotation.XmlAccessorType;
  3. import javax.xml.bind.annotation.XmlRootElement;
  4. import javax.xml.bind.annotation.XmlType;
  5. @XmlRootElement(name = "book")
  6. // If you want you can define the order in which the fields are written
  7. // Optional
  8. @XmlType(propOrder = { "name", "author", "publisher", "isbn" })
  9. public class Book {
  10. private String name;
  11. private Author author;
  12. private String publisher;
  13. private String isbn;
  14. // If you like the variable name, e.g. "name", you can easily change this
  15. // name for your XML-Output:
  16. public String getName() {
  17. return name;
  18. }
  19. public void setName(String name) {
  20. this.name = name;
  21. }
  22. public Author getAuthor() {
  23. return author;
  24. }
  25. public void setAuthor(Author author) {
  26. this.author = author;
  27. }
  28. public String getPublisher() {
  29. return publisher;
  30. }
  31. public void setPublisher(String publisher) {
  32. this.publisher = publisher;
  33. }
  34. public String getIsbn() {
  35. return isbn;
  36. }
  37. public void setIsbn(String isbn) {
  38. this.isbn = isbn;
  39. }
  40. }
  1. package com.jaxb.first;
  2. import javax.xml.bind.annotation.XmlAttribute;
  3. public class Author {
  4. private String name;
  5. private int age;
  6. @XmlAttribute
  7. public String getName() {
  8. return name;
  9. }
  10. public void setName(String name) {
  11. this.name = name;
  12. }
  13. public int getAge() {
  14. return age;
  15. }
  16. public void setAge(int age) {
  17. this.age = age;
  18. }
  19. }
  1. package com.jaxb.first;
  2. import java.util.ArrayList;
  3. import javax.xml.bind.annotation.XmlElement;
  4. import javax.xml.bind.annotation.XmlElementWrapper;
  5. import javax.xml.bind.annotation.XmlRootElement;
  6. @XmlRootElement(namespace="abc")
  7. public class Bookstore {
  8. // XmLElementWrapper generates a wrapper element around XML representation
  9. @XmlElementWrapper(name = "bookList")
  10. // XmlElement sets the name of the entities
  11. @XmlElement(name = "book")
  12. private ArrayList<Book> bookList;
  13. private String name;
  14. private String location;
  15. public void setBookList(ArrayList<Book> bookList) {
  16. this.bookList = bookList;
  17. }
  18. public ArrayList<Book> getBooksList() {
  19. return bookList;
  20. }
  21. public String getName() {
  22. return name;
  23. }
  24. public void setName(String name) {
  25. this.name = name;
  26. }
  27. public String getLocation() {
  28. return location;
  29. }
  30. public void setLocation(String location) {
  31. this.location = location;
  32. }
  33. }
  1. package com.jaxb.first;
  2. import java.io.FileReader;
  3. import java.io.FileWriter;
  4. import java.io.IOException;
  5. import java.io.Writer;
  6. import java.util.ArrayList;
  7. import javax.xml.bind.JAXBContext;
  8. import javax.xml.bind.JAXBException;
  9. import javax.xml.bind.Marshaller;
  10. import javax.xml.bind.Unmarshaller;
  11. import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
  12. public class BookMain {
  13. private static final String BOOKSTORE_XML = "./bookstore-jaxb.xml";
  14. public static void main(String[] args) throws JAXBException, IOException {
  15. ArrayList<Book> bookList = new ArrayList<Book>();
  16. // create books
  17. Book book1 = new Book();
  18. book1.setIsbn("978-0060554736");
  19. book1.setName("The Game");
  20. Author a = new Author();
  21. a.setAge(28);
  22. a.setName("Gosling");
  23. book1.setAuthor(a);
  24. book1.setPublisher("Harpercollins");
  25. bookList.add(book1);
  26. Book book2 = new Book();
  27. book2.setIsbn("978-3832180577");
  28. book2.setName("Feuchtgebiete");
  29. Author a2 = new Author();
  30. a2.setAge(32);
  31. a2.setName("James Green");
  32. book2.setAuthor(a2);
  33. book2.setPublisher("Dumont Buchverlag");
  34. bookList.add(book2);
  35. // create bookstore, assigning book
  36. Bookstore bookstore = new Bookstore();
  37. bookstore.setName("Fraport Bookstore");
  38. bookstore.setLocation("Frankfurt Airport");
  39. bookstore.setBookList(bookList);
  40. // create JAXB context and instantiate marshaller
  41. JAXBContext context = JAXBContext.newInstance(Bookstore.class);
  42. Marshaller m = context.createMarshaller();
  43. NamespacePrefixMapper mapper = new PreferredMapper();
  44. m.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);
  45. m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
  46. m.marshal(bookstore, System.out);
  47. Writer w = null;
  48. try {
  49. w = new FileWriter(BOOKSTORE_XML);
  50. m.marshal(bookstore, w);
  51. } finally {
  52. try {
  53. w.close();
  54. } catch (Exception e) {
  55. }
  56. }
  57. // get variables from our xml file, created before
  58. System.out.println();
  59. System.out.println("Output from our XML File: ");
  60. Unmarshaller um = context.createUnmarshaller();
  61. Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(
  62. BOOKSTORE_XML));
  63. for (int i = 0; i < bookstore2.getBooksList().toArray().length; i++) {
  64. System.out.println("Book " + (i + 1) + ": "
  65. + bookstore2.getBooksList().get(i).getName() + " from "
  66. + bookstore2.getBooksList().get(i).getAuthor());
  67. }
  68. }
  69. public static class PreferredMapper extends NamespacePrefixMapper {
  70. @Override
  71. public String getPreferredPrefix(String namespaceUri,
  72. String suggestion, boolean requirePrefix) {
  73. return "pre";
  74. }
  75. }
  76. }

看下输出结果:

  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  2. <pre:bookstore xmlns:pre="abc">
  3. <bookList>
  4. <book>
  5. <name>The Game</name>
  6. <author name="Gosling">
  7. <age>28</age>
  8. </author>
  9. <publisher>Harpercollins</publisher>
  10. <isbn>978-0060554736</isbn>
  11. </book>
  12. <book>
  13. <name>Feuchtgebiete</name>
  14. <author name="James Green">
  15. <age>32</age>
  16. </author>
  17. <publisher>Dumont Buchverlag</publisher>
  18. <isbn>978-3832180577</isbn>
  19. </book>
  20. </bookList>
  21. <location>Frankfurt Airport</location>
  22. <name>Fraport Bookstore</name>
  23. </pre:bookstore>
  24. Output from our XML File:
  25. Book 1: The Game from com.jaxb.first.Author@1774b9b
  26. Book 2: Feuchtgebiete from com.jaxb.first.Author@104c575

OK 是我们想要的格式吧。 那么事情就解决了

值 得注意的是:如果你要对属性做注解,必须将注解写在属性的get方法上, 就如我们Author类中的 @XmlAttribute那样,否则运行的时候他会提示:the same element name xxx..

2.Xml与多个对象的映射(聚合或组合)及注意事项的更多相关文章

  1. [原创]java WEB学习笔记81:Hibernate学习之路--- 对象关系映射文件(.hbm.xml):hibernate-mapping 节点,class节点,id节点(主键生成策略),property节点,在hibernate 中 java类型 与sql类型之间的对应关系,Java 时间和日期类型的映射,Java 大对象类型 的 映射 (了解),映射组成关系

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  2. [原创]java WEB学习笔记77:Hibernate学习之路---Hibernate 版本 helloword 与 解析,.环境搭建,hibernate.cfg.xml文件及参数说明,持久化类,对象-关系映射文件.hbm.xml,Hibernate API (Configuration 类,SessionFactory 接口,Session 接口,Transaction(事务))

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  3. 3hibernate核心对象关系映射 xxx.hbm.xml

    Hibernate的核心就是对象关系映射: 加载映射文件的两种方式: 第一种:<mapping resource="com/bie/lesson02/crud/po/employee. ...

  4. 死去活来,而不变质:Domain Model(领域模型) 和 EntityFramework 如何正确进行对象关系映射?

    写在前面 阅读目录: 设计误区 数据库已死 枚举映射 关联映射 后记 在上一篇<一缕阳光:DDD(领域驱动设计)应对具体业务场景,如何聚焦 Domain Model(领域模型)?>博文中, ...

  5. Hibernate(开放源代码的对象关系映射框架)

    Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自 ...

  6. ORM即 对象-关系映射(转自:微冷的雨)

    ORM即 对象-关系映射: 将数据库中的数据关系表,映射为实体对象. 灵动思绪EF(Entity FrameWork) 作者: 微冷的雨  来源: 博客园  发布时间: 2013-01-22 16:2 ...

  7. LLBL Gen Pro 4.2 Lite 免费的对象关系映射开发框架与工具

    LLBL Gen Pro是一款优秀的对象关系映射开发框架,自2003年发布以来,一直有广泛的客户群.LLBL Gen Pro有几个标志性的版本,2.5/2.6是一个很稳定的版本,公司的一些旧的项目仍然 ...

  8. hibernate(四)__由表逆向创建Domain对象和对象关系映射文件

    之前我们是手写Domain对象和对象关系映射文件->然后生成数据库中的Table. 现在我们反过来先在数据库中建好Table->然后用工具生成Domain对象和对象关系映射文件. 步骤: ...

  9. android对象关系映射框架ormlite之一对多(OneToMany)

    前两天,用ormlite对单张表进行了基本的操作,但是,我们知道通常情况对于单张表格进行操作在实际情况中很前两天不现实,那么ormlite能否像Hibenate那样实现多张表之间的一对多,多对多(即O ...

随机推荐

  1. 【SRM 717 div2 A】 NiceTable

    Problem Statement You are given a vector t that describes a rectangular table of zeroes and ones. Ea ...

  2. 洛谷 P3663 [USACO17FEB]Why Did the Cow Cross the Road III S

    P3663 [USACO17FEB]Why Did the Cow Cross the Road III S 题目描述 Why did the cow cross the road? Well, on ...

  3. UVa 112 树求和

    题意:给定一个数字,以及一个描写叙述树的字符序列,问存不存在一条从根到某叶子结点的路径使得其和等于那个数. 难点在于怎样处理字符序列.由于字符间可能有空格.换行等. 思路:本来想着用scanf的(后发 ...

  4. google浏览器修改网页字符编码

    google浏览器修改网页字符编码 直接在google浏览器的应用拓展程序里面搜 Charset,第一个就是 于是就有了

  5. idea里新建maven项目时,在new module页面,一直显示loading archetype list...

    不知道什么时候开始,在idea里新建maven项目时,在new module页面,一直显示loading archetype list....,导致一直没办法新建.后来我以为是防火墙问题,各种设置还是 ...

  6. 机器学习(三) Jupyter Notebook, numpy和matplotlib的详细使用 (下)

    七.Numpy中的矩阵运算 八.Numpy中的聚合运算 九.Numpy中的arg运算 十.Numpy中的比较和Fancy Indexing 十一.Matplotlib数据可视化基础 十二.数据加载和简 ...

  7. vue中剖析中的一些方法

    1 判断属性 71 -81 var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Check whether the object h ...

  8. Windows环境下VMware虚拟机的自启动与自动关机--命令行操作

    .设置开机免密登录系统 1. 按下Windows + R 组合键,输入“netplwiz”,点击回车. 2. 去除需要密码登录的勾. 3. 如果需要密码,输入密码,点击确认.   二.编辑vmware ...

  9. happy Mom ——php mysqli DES加密

    看完<爱你就像爱生命>这本书,真的看出小波哥很有才,跟小波哥比起来,我唯一拿的出手的可能就是我比他的颜值了.想起一句话,人不是因为美丽而可爱,而是因为可爱而美丽.所以我对我的要求是,继续修 ...

  10. codeforces1114D. Flood Fill(区间Dp)

    传送门: 解题思路: 区间Dp,发现某一个区间修改后区间颜色一定为左边或右边的颜色. 那么只需要设方程$f_(l,r,0/1)$表示区间$[l,r]$染成左/右颜色的最小代价 转移就是枚举左右颜色就好 ...