1. 程式人生 > >JAXB的應用之二---------Xml與多個物件的對映(聚合或組合)及注意事項

JAXB的應用之二---------Xml與多個物件的對映(聚合或組合)及注意事項

   在我們的實際應用中,Xml中的結構往往不止這麼簡單,一般都會有2,3層。也就是說如果對映成物件就是聚合(組合)的情況 。

就用我們上一章的例子繼續來講,簡單我們的Book的author現在不止是一個String型別的名子,他是一個物件Author,幷包含作者的相關個人資訊。那我們怎麼做列?

直接看程式碼

package com.jaxb.first;

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "book")
// If you want you can define the order in which the fields are written
// Optional
@XmlType(propOrder = { "name", "author", "publisher", "isbn" })
public class Book {

	private String name;
	private Author author;
	private String publisher;
	private String isbn;

	// If you like the variable name, e.g. "name", you can easily change this
	// name for your XML-Output:
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}


	public Author getAuthor() {
		return author;
	}

	public void setAuthor(Author author) {
		this.author = author;
	}

	public String getPublisher() {
		return publisher;
	}

	public void setPublisher(String publisher) {
		this.publisher = publisher;
	}

	public String getIsbn() {
		return isbn;
	}

	public void setIsbn(String isbn) {
		this.isbn = isbn;
	}

}

package com.jaxb.first;

import javax.xml.bind.annotation.XmlAttribute;

public class Author {

	
	private String name;
	private int age;
	
	@XmlAttribute
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	
	
}


package com.jaxb.first;

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(namespace="abc")
public class Bookstore {

	// XmLElementWrapper generates a wrapper element around XML representation
	@XmlElementWrapper(name = "bookList")
	// XmlElement sets the name of the entities
	@XmlElement(name = "book")
	private ArrayList<Book> bookList;
	private String name;
	private String location;

	public void setBookList(ArrayList<Book> bookList) {
		this.bookList = bookList;
	}

	public ArrayList<Book> getBooksList() {
		return bookList;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}
}
 
package com.jaxb.first;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.sun.xml.bind.marshaller.NamespacePrefixMapper;

public class BookMain {

	private static final String BOOKSTORE_XML = "./bookstore-jaxb.xml";

	public static void main(String[] args) throws JAXBException, IOException {

		ArrayList<Book> bookList = new ArrayList<Book>();

		// create books
		Book book1 = new Book();
		book1.setIsbn("978-0060554736");
		book1.setName("The Game");
		Author a = new Author();
		a.setAge(28);
		a.setName("Gosling");
		book1.setAuthor(a);
		book1.setPublisher("Harpercollins");
		bookList.add(book1);

		Book book2 = new Book();
		book2.setIsbn("978-3832180577");
		book2.setName("Feuchtgebiete");
		Author a2 = new Author();
		a2.setAge(32);
		a2.setName("James Green");
		book2.setAuthor(a2);
		book2.setPublisher("Dumont Buchverlag");
		bookList.add(book2);

		// create bookstore, assigning book
		Bookstore bookstore = new Bookstore();
		bookstore.setName("Fraport Bookstore");
		bookstore.setLocation("Frankfurt Airport");
		bookstore.setBookList(bookList);

		// create JAXB context and instantiate marshaller
		JAXBContext context = JAXBContext.newInstance(Bookstore.class);
		Marshaller m = context.createMarshaller();
		NamespacePrefixMapper mapper = new PreferredMapper();
		m.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);

		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		m.marshal(bookstore, System.out);

		Writer w = null;
		try {
			w = new FileWriter(BOOKSTORE_XML);
			m.marshal(bookstore, w);
		} finally {
			try {
				w.close();
			} catch (Exception e) {
			}
		}

		// get variables from our xml file, created before
		System.out.println();
		System.out.println("Output from our XML File: ");
		Unmarshaller um = context.createUnmarshaller();
		Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(
				BOOKSTORE_XML));

		for (int i = 0; i < bookstore2.getBooksList().toArray().length; i++) {
			System.out.println("Book " + (i + 1) + ": "
					+ bookstore2.getBooksList().get(i).getName() + " from "
					+ bookstore2.getBooksList().get(i).getAuthor());
		}

	}

	public static class PreferredMapper extends NamespacePrefixMapper {
		@Override
		public String getPreferredPrefix(String namespaceUri,
				String suggestion, boolean requirePrefix) {
			return "pre";
		}

		
	}
}


看下輸出結果:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<pre:bookstore xmlns:pre="abc">
    <bookList>
        <book>
            <name>The Game</name>
            <author name="Gosling">
                <age>28</age>
            </author>
            <publisher>Harpercollins</publisher>
            <isbn>978-0060554736</isbn>
        </book>
        <book>
            <name>Feuchtgebiete</name>
            <author name="James Green">
                <age>32</age>
            </author>
            <publisher>Dumont Buchverlag</publisher>
            <isbn>978-3832180577</isbn>
        </book>
    </bookList>
    <location>Frankfurt Airport</location>
    <name>Fraport Bookstore</name>
</pre:bookstore>

Output from our XML File: 
Book 1: The Game from [email protected]
Book 2: Feuchtgebiete from [email protected]

OK 是我們想要的格式吧。 那麼事情就解決了

   值 得注意的是:如果你要對屬性做註解,必須將註解寫在屬性的get方法上, 就如我們Author類中的 @XmlAttribute那樣,否則執行的時候他會提示:the same element name xxx..

相關推薦

JAXB應用---------Xml物件對映聚合組合注意事項

   在我們的實際應用中,Xml中的結構往往不止這麼簡單,一般都會有2,3層。也就是說如果對映成物件就是聚合(組合)的情況 。 就用我們上一章的例子繼續來講,簡單我們的Book的author現在不止是一個String型別的名子,他是一個物件Author,幷包含作者的相關個人

爬蟲實現 -- 爬蟲實現解析函式

目標 完成spider中如果解析函式呼叫的封裝 掌握getattr的方法 完成通過meta在不通過的解析函式中傳遞資料的方法 1. 爬蟲實現多個解析函式的意義 2 響應物件的解析方法封裝 為response物件封裝xpath、正則、json、等方法和屬

SSM框架Mybatis同時傳入物件普通引數

當傳入多個檔案時,mapper介面檔案的方法引數要使用@param(“xx”)註釋。 例子: mapper: //Student是物件,age是String型別。 int getPojo(@param("student") Student student, @param("age") S

php面試題——數據結構和算法高級部分

ash item name queue lis 雙向 joseph test 數據結構和算法 二、數據結構和算法 1.使對象可以像數組一樣進行foreach循環,要求屬性必須是私有。(Iterator模式的PHP5實現,寫一類實現Iterator接口)(騰訊) <?

協程等待非同步呼叫list or dict

from tornado import gen from tornado.httpclient import AsyncHTTPClient @gen.coroutine def coroutine_visit_list(): http_client = AsyncHTTPClient()

springmvc接收一個類物件資料提交整個表格資料

<body>     <form action="${contextPath}/user/testdemo" id="uform" method="post">     <table >     <td>使用者名稱</td><td>密碼&

資料庫主鍵聯合主鍵

建立某表,需要兩個主鍵(INST_ID,INST_RESP_CODE) CREATE TABLE CODE_CONVERTER_20170806 ( INST_ID CHARACTER(4) NO

線上考試系統()---單選選多種題型radio和checkbox

同一個頁面有多個題型是如何實現的呢?首先就單選題來說,我們都知道radio單選框是以name來分組的,一個組裡只能有一個radio被選中,所以在設計的時候,為了與後臺之間的傳值,就要根據一定的命名規則,為每個題附一個不同的name,這樣才能保證可以在每道題都可以

jupyter notebook 安裝版本kernelpython2 和python3

預設是python2,在tensorflow中需要python3: source activate tensorflow conda install notebook ipykernel ip

Git管理遠端倉庫GitHub和Coding

兩個空程式碼倉庫 如果是兩個倉庫都是空的,就直接在 .git/config 中新增遠端地址 [remote "origin"] url = https://github.com/younglaker/octjs.git url = https

spring接收json格式的物件引數變通法

兩種方法 方法1 如果使用spring mvc同客戶端通訊,完全使用json資料格式,需要如下定義一個RequestMapping @Controller public class TestController{ @RequestMapping("\test"

設計模式-代理類proxy:一個介面實現類基於spring框架

根據前臺返回的不同引數,選擇一個介面不同的實現類來實現不同業務邏輯,我們用到了proxy代理類。 首先是spring.xml 配置檔案 如下:(proxy 表示代理類  ××ServiceImpl 表示實現類) <bean id="介面名稱" >      

active mq 消費者實戰釋出訂閱模式

            注意:所有的配置檔案都在src檔案下            宣告:  在這裡不講activemq 是什麼,本人只是根據平時用到的東西整理一下希望對大家有所幫助。         首先是生產者的配置檔案 <?xml version="1.0" e

NetCore+AutoMapper物件對映到一個Dto物件

  目錄 一、定義源對映類和被對映類DTO 二、注入AutoMapper 三、配置對映 四、呼叫AutoMapper完成賦值 五、執行測試   一、定義源對映物件 為了體現AutoMapper對映特性,在SocialAttribute中的Name屬性沒有定義在People中,People的

目標檢測訓練opencv自帶的分類器opencv_haartraining opencv_traincascade

    最權威的說明,參考官方使用手冊:     http://www.OpenCV.org.cn/opencvdoc/2.3.2/html/doc/user_guide/ug_traincasca

Angular-ui-router進階巢狀檢視檢視組合使用

ui-router巢狀檢視 巢狀檢視是ui-router不同於ng-route的最大區別之一,也是ui-router受到大眾青睞的主要原因。接下來跟小編直接上手做一下簡單的巢狀檢視(Nested Views)。 上面是本次示例的佈局,有導航欄、側邊欄、檢視1及其子孫檢

Spring Boot 在Netty上開發WebSocket和HTTP應用 -- HTTP Handler含上傳和下載處理鏈

接上篇。 因業務需要,在一個埠開啟普通的HTTP(S)服務,配合客戶端實現使用者登入驗證,使用者檔案上傳、檔案下載等功能。 在Netty中的處理方式如下: 處理鏈初始化如下,注意途中紅色方框處內容的順序。 接下來是NETTY封裝檔案的下載處理。注意下

tensorflow 一個矩陣矩陣相乘時的計算方法維和三維張量相乘為例

當tensor1 的 shape 為[k, m, n], tensor2 的 shape 為 [n, p]時, 要將tensor1的後兩維構成的k個矩陣與tensor2中的矩陣做矩陣乘法得到 shape 為[k, m, p]的向量 解決辦法: 1,我們知道Tenso

Excel Power Query經典應用維表轉一維表

office excel power 技能 經典 Excel Power Query經典應用之二維表轉一維表 將一個二維表格轉為一維表格,是我們經常要做的事,目的是為了將數據做更好的分析。但Excel普通的轉換的方式卻比較麻煩。不過不用擔心。利用Excel的Power Quer

C#使用Socket實現一個socket服務器socket客戶端通信

當前 rec inf hide 負責 new 數據庫 class 多臺   在分布式調度系統中,如果要實現調度服務器與多臺計算節點服務器之間通信,采用socket來實現是一種實現方式,當然我們也可以通過數據存儲任務,子節點來完成任務,但是往往使用數據作為任務存儲都需要定制開