Java 如何使用JAXB整理多个对象?
我正在尝试整理多个对象,例如通过Java 如何使用JAXB整理多个对象?,java,web-services,jaxb,Java,Web Services,Jaxb,我正在尝试整理多个对象,例如通过setBookslst()添加到书目中的Book。我开始使用这个JAXBContext设置: jaxbContext = JAXBContext.newInstance(BookLists.class); 及 但是,我收到了以下运行时异常: javax.xml.bind.JAXBException:com.jaxb.example.marshall.Book或任何 其超类的定义在此上下文中是已知的] 我的类型定义如下 书籍:- @XmlRootElement(n
setBookslst()
添加到书目中的Book
。我开始使用这个JAXBContext
设置:
jaxbContext = JAXBContext.newInstance(BookLists.class);
及
但是,我收到了以下运行时异常:
javax.xml.bind.JAXBException:com.jaxb.example.marshall.Book或任何
其超类的定义在此上下文中是已知的]
我的类型定义如下
书籍:-
@XmlRootElement(name="book")
public class Book {
private String title;
private int year;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
@XmlRootElement(name="lists")
public class BookLists {
List<Book> bookslst;
public List getBookslst() {
return bookslst;
}
public void setBookslst(List bookslst) {
this.bookslst = bookslst;
}
}
Book book;
BookLists lists=new BookLists();
List lst=new ArrayList();
book = new Book();
book.setTitle("Book title");
book.setYear(2010);
lst.add(book);
book = new Book();
book.setTitle("Book title1");
book.setYear(2011);
lst.add(book);
lists.setBookslst(lst);
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(BookLists.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter result = new StringWriter();
jaxbMarshaller.marshal(lists, result);
String xml = result.toString();
System.out.println(xml);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
书目:-
@XmlRootElement(name="book")
public class Book {
private String title;
private int year;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
@XmlRootElement(name="lists")
public class BookLists {
List<Book> bookslst;
public List getBookslst() {
return bookslst;
}
public void setBookslst(List bookslst) {
this.bookslst = bookslst;
}
}
Book book;
BookLists lists=new BookLists();
List lst=new ArrayList();
book = new Book();
book.setTitle("Book title");
book.setYear(2010);
lst.add(book);
book = new Book();
book.setTitle("Book title1");
book.setYear(2011);
lst.add(book);
lists.setBookslst(lst);
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(BookLists.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter result = new StringWriter();
jaxbMarshaller.marshal(lists, result);
String xml = result.toString();
System.out.println(xml);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我正在尝试放置@xmlseea
注释(参考:-)。此注释在我的版本中不可用。尝试将这两个类添加到JAXBContext.newInstance调用中
JAXBContext.newInstance(BookLists.class, Book.class);
使用您的类可以:
public static void main(String [] args) throws JAXBException {
BookLists books = new BookLists();
String [] titles = {"To Kill a Mockingbird", "Twelve Angry Men", "Are You My Mother", "Green Eggs And Ham"};
List<Book> list = new ArrayList<Book>();
for (String title : titles) {
Book book = new Book();
book.setTitle(title);
list.add(book);
}
books.setBookslst(list);
JAXBContext jc = JAXBContext.newInstance(BookLists.class, Book.class);
Marshaller nm = jc.createMarshaller();
nm.setProperty("jaxb.formatted.output", true);
nm.marshal(books, System.out);
}
publicstaticvoidmain(字符串[]args)抛出jaxbeexception{
BookLists books=新的BookLists();
String[]titles={“杀死一只知更鸟”、“十二个愤怒的人”、“你是我的母亲”、“绿鸡蛋和火腿”};
列表=新的ArrayList();
for(字符串标题:标题){
书=新书();
书名(书名);
列表。添加(书本);
}
图书目录;
JAXBContext jc=JAXBContext.newInstance(BookLists.class,Book.class);
Marshaller nm=jc.createMarshaller();
setProperty(“jaxb.formatted.output”,true);
nm.marshal(图书,系统输出);
}
输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<lists>
<book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="book">
<title>To Kill a Mockingbird</title>
<year>0</year>
</book>
<book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="book">
<title>Twelve Angry Men</title>
<year>0</year>
</book>
<book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="book">
<title>Are You My Mother</title>
<year>0</year>
</book>
<book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="book">
<title>Green Eggs And Ham</title>
<year>0</year>
</book>
</lists>
杀死一只知更鸟
0
十二个愤怒的人
0
你是我妈妈吗
0
绿鸡蛋和火腿
0
使用
还可将BoolList定义如下:
@XmlRootElement(name="lists")
public class BookLists {
List<Book> bookslst;
public List<Book> getBookslst() {
return bookslst;
}
public void setBookslst(List<Book> bookslst) {
this.bookslst = bookslst;
}
}
@XmlRootElement(name=“lists”)
公开课书目{
清单1;
公共列表getbookslt(){
返回bookslt;
}
公共无效setBookslst(列表bookslst){
this.bookslt=bookslt;
}
}
默认情况下,JAXB(JSR-222)实现检查公共访问器方法。您可以在get/set方法中的列表中添加Book
参数
public List<Book> getBookslst() {
return bookslst;
}
public void setBookslst(List<Book> bookslst) {
this.bookslst = bookslst;
}
您还可以指定JAXB实现内省字段而不是属性:
@XmlRootElement(name="lists")
@XmlAccessorType(XmlAccessType.FIELD)
public class BookLists {
List<Book> bookslst;
}
演示
package forum12323397;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Lists.class, Book.class);
Lists<Book> lists = new Lists<Book>();
Book book1 = new Book();
book1.setTitle("A Book");
book1.setYear(2001);
lists.getValues().add(book1);
Book book2 = new Book();
book2.setTitle("Another Book");
book2.setYear(2007);
lists.getValues().add(book2);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(lists, System.out);
}
}
UM12323397的包;
导入javax.xml.bind.*;
公开课演示{
公共静态void main(字符串[]args)引发异常{
JAXBContext jc=JAXBContext.newInstance(Lists.class,Book.class);
列表=新列表();
Book book1=新书();
书1.书名(“一本书”);
第1册.设定年份(2001年);
lists.getValues().add(book1);
Book book2=新书();
书籍2.书名(“另一本书”);
第2册:设定年(2007年);
lists.getValues().add(book2);
Marshaller=jc.createMarshaller();
setProperty(marshaller.JAXB_格式化的_输出,true);
marshaller.marshall(列表,系统输出);
}
}
输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<lists>
<book>
<title>A Book</title>
<year>2001</year>
</book>
<book>
<title>Another Book</title>
<year>2007</year>
</book>
</lists>
书
2001
另一本书
2007
添加注释@xmlsealse(value={Book.class})
到书单班。现在应该可以工作了。我有一个工作示例:
1) XML:
4) 主要
包jaxbtest;
导入java.io.ByteArrayInputStream;
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.FileReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.util.ArrayList;
导入java.util.array;
导入javax.xml.bind.JAXBContext;
导入javax.xml.bind.JAXBException;
导入javax.xml.bind.Marshaller;
导入javax.xml.bind.Unmarshaller;
公共类图书管理员{
私有静态最终字符串BOOKSTORE_XML=“./BOOKSTORE jaxb.XML”;
公共静态void main(字符串[]args)抛出jaxbeexception、IOException{
ArrayList bookList=新建ArrayList();
//创作书籍
Book book1=新书();
第1册setIsbn(“978-0060554736”);
book1.setName(“游戏”);
书1.作者(“尼尔·施特劳斯”);
book1.setPublisher(“Harpercollins”);
图书目录。添加(第1册);
Book book2=新书();
第2册setIsbn(“978-3832180577”);
账簿2.设置名称(“Feuchtgebiete”);
第二册作者(“夏洛特·罗奇”);
书籍2.setPublisher(“Dumont Buchverlag”);
增加(第2册);
//创建书店,分配图书
书店=新书店();
bookstore.setName(“Fraport书店”);
书店。设置地点(“法兰克福机场”);
书店.setBookList(图书目录);
//创建JAXB上下文并实例化marshaller
JAXBContext context=JAXBContext.newInstance(Bookstore.class);
Marshaller m=context.createMarshaller();
m、 setProperty(Marshaller.JAXB_格式的_输出,Boolean.TRUE);
//写入System.out
m、 元帅(书店,系统输出);
//写入文件
m、 封送员(书店,新文件(书店XML));
//从之前创建的xml文件中获取变量
System.out.println();
System.out.println(“来自XML文件的输出:”);
Unmarshaller um=context.createUnmarshaller();
bookstore2=(Bookstore)um.unmarshal(新文件阅读器(Bookstore_XML));
ArrayList=bookstore2.getBooksList();
用于(书籍:列表){
System.out.println(“Book:+Book.getName()+”from”
+book.getAuthor());
}
/*
字符串xmlStr=readFileToString(BOOKSTORE_XML);
Bookstore Bookstore=getPartial3(Bookstore.class,xmlStr);
对于(图书b:bookstore.getBooksList())
System.out.println(b.getName()+“----”+b.getAuthor());
xmlStr=readFileToString(“./listapplicationofferings.xml”);
ApplianceList bookstore1=getPartial3(ApplianceList.class,xmlStr);
对于(设备b:bookstore1.getBooksList())
System.out.println(b.getName()+“----”+b.getDescription());
*/
//88888
//字符串xmlStr=readFileToString(“./ListStorageOffices.xml”);
//StorageOffices-storageOfferingsList=jaxbXmlString2Class(storageOffices.class,xmlStr);
StorageOffices-storageOfferingsList=jaxbXmlFile2Class(StorageOffices.class.“。/listStorageOff
package forum12323397;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Lists.class, Book.class);
Lists<Book> lists = new Lists<Book>();
Book book1 = new Book();
book1.setTitle("A Book");
book1.setYear(2001);
lists.getValues().add(book1);
Book book2 = new Book();
book2.setTitle("Another Book");
book2.setYear(2007);
lists.getValues().add(book2);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(lists, System.out);
}
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<lists>
<book>
<title>A Book</title>
<year>2001</year>
</book>
<book>
<title>Another Book</title>
<year>2007</year>
</book>
</lists>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<bookstore>
<bookList>
<book>
<author>Neil Strauss</author>
<title>The Game</title>
<publisher>Harpercollins</publisher>
<isbn>978-0060554736</isbn>
</book>
<book>
<author>Charlotte Roche</author>
<title>Feuchtgebiete</title>
<publisher>Dumont Buchverlag</publisher>
<isbn>978-3832180577</isbn>
</book>
</bookList>
<location>Frankfurt Airport</location>
<name>Fraport Bookstore</name>
</bookstore>
package jaxbtest;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="bookstore") // (namespace = "de.vogella.xml.jaxb.model", name="bookstore")
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 jaxbtest;
import javax.xml.bind.annotation.XmlElement;
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 = { "author", "name", "publisher", "isbn" })
public class Book {
private String name;
private String 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:
@XmlElement(name = "title")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String 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 jaxbtest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
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");
book1.setAuthor("Neil Strauss");
book1.setPublisher("Harpercollins");
bookList.add(book1);
Book book2 = new Book();
book2.setIsbn("978-3832180577");
book2.setName("Feuchtgebiete");
book2.setAuthor("Charlotte Roche");
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();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// Write to System.out
m.marshal(bookstore, System.out);
// Write to File
m.marshal(bookstore, new File(BOOKSTORE_XML));
// 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));
ArrayList<Book> list = bookstore2.getBooksList();
for (Book book : list) {
System.out.println("Book: " + book.getName() + " from "
+ book.getAuthor());
}
/*
String xmlStr = readFileToString(BOOKSTORE_XML);
Bookstore bookstore = getPartial3(Bookstore.class ,xmlStr);
for (Book b : bookstore.getBooksList())
System.out.println(b.getName()+ " ---- " + b.getAuthor() );
xmlStr = readFileToString("./listApplianceOfferings.xml");
ApplianceList bookstore1 = getPartial3(ApplianceList.class ,xmlStr);
for (Appliance b : bookstore1.getBooksList())
System.out.println(b.getName() + " ---- " + b.getDescription() );
*/
//88888
// String xmlStr = readFileToString("./listStorageOfferings.xml");
// StorageOfferings storageOfferingsList = jaxbXmlString2Class(StorageOfferings.class ,xmlStr);
StorageOfferings storageOfferingsList = jaxbXmlFile2Class(StorageOfferings.class ,"./listStorageOfferings.xml");
for (StorageOffering s : storageOfferingsList.getStorageOfferingList() )
System.out.println("8888--> "+ s.getName() + " ---- " + s.getId() );
//99999
}//main
private static void getPartial() {
// get variables from our xml file, created before
System.out.println();
System.out.println("Output from our XML File: ");
Unmarshaller um;
try {
JAXBContext context = JAXBContext.newInstance(Bookstore.class);;
um = context.createUnmarshaller();
// um.setEventHandler(new DefaultValidationEventHandler());
FileReader fileReader = new FileReader(BOOKSTORE_XML);
Bookstore bookstore = (Bookstore) um.unmarshal(fileReader );
ArrayList<Book> list = bookstore.getBooksList();
for (Book book : list) {
System.out.println("Book: " + book.getName() + " from "
+ book.getAuthor());
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void getPartial1() {
// get variables from our xml file, created before
System.out.println();
System.out.println("Output from our XML File: ");
Unmarshaller um;
try {
JAXBContext context = JAXBContext.newInstance(ApplianceList.class);;
um = context.createUnmarshaller();
// um.setEventHandler(new DefaultValidationEventHandler());
FileReader fileReader = new FileReader("./listApplianceOfferings.xml");
ApplianceList alist = (ApplianceList) um.unmarshal(fileReader );
ArrayList<Appliance> list = alist.getBooksList();
for (Appliance book : list) {
System.out.println("appliance: " + book.getName() + " from "
+ book.getDescription());
}
} catch (Exception e) {
e.printStackTrace();
}
}
//-------------------
private static <T> T getPartial2(Class<T> cls, String fname) {
// get variables from our xml file, created before
System.out.println();
System.out.println("Output from our XML File: ");
Unmarshaller um;
T alist = null;
try {
JAXBContext context = JAXBContext.newInstance(cls);;
um = context.createUnmarshaller();
// um.setEventHandler(new DefaultValidationEventHandler());
FileReader fileReader = new FileReader(fname);
alist = (T) um.unmarshal(fileReader );
//ArrayList<?> list = alist.getBooksList();
// for (Appliance book : list) {
// System.out.println("appliance: " + book.getName() + " from "
// + book.getDescription());
// }
} catch (Exception e) {
e.printStackTrace();
}
return alist;
}
//-------------------
private static <T> T jaxbXmlFile2Class(Class<T> cls, String fileName) {
FileReader fr = null;
char [] cbuf = null;
try {
fr = new FileReader(fileName);
cbuf = new char[3000];
Arrays.fill(cbuf, ' ');
fr.read(cbuf);
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try { fr.close(); }
catch (IOException e) {
e.printStackTrace();
}
}
String s = new String(cbuf);
return jaxbXmlString2Class(cls, s);
}
@SuppressWarnings("unchecked")
private static <T> T jaxbXmlString2Class(Class<T> cls, String xmlStr) {
// get variables from our xml file, created before
System.out.println();
System.out.println("Output from our XML File: ");
Unmarshaller um;
T alist = null;
try {
JAXBContext context = JAXBContext.newInstance(cls);;
um = context.createUnmarshaller();
System.out.println(xmlStr);
InputStream is = new ByteArrayInputStream(xmlStr.getBytes());
alist = (T) um.unmarshal( is );
} catch (Exception e) {
e.printStackTrace();
}
return alist;
}
}
<lists>
<book>
<title>A Book</title>
<year>2001</year>
</book>
<book>
<title>Another Book</title>
<year>2007</year>
</book>
</lists>
<lists>
<book>
<title>A Book</title>
<year>2001</year>
<title>Another Book</title>
<year>2007</year>
</book>
</lists>