jaxb:Java Architecture for XML Binding
1.Bind the Schema
将XSD文件解析成javabean
在java1.5一下的版本 需要下载JAXB
在java1.6中,java已经将JAXB集成进来
此时我们只要进入到%JAVA_HOME%/bin目录下执行命令:xjc books.xsd -p test.jaxb -d work
其中参数-p表示Package -d表示生产文件的Directry;
之后便会生成javabean对象
2、Unmarshalling an XML document 解组XML文档
javax.xml.bind.JAXBContext 是java1.6新加进来的包
JAXBContext jc = JAXBContext.newInstance("test.jaxb"); //test.jaxb是XML Schema所生成的javaBean所在的包名
Unmarshaller unmarshaller = jc.createUnmarshaller(); //创建借组程序对象
Collection collection= (Collection) unmarshaller.unmarshal(new File( "books.xml")); //指定借组对象 其中Collection对象是bind Schema都会生成的一个类
从该类派生的对象可以获取根节点元素,再从根节点元素获取各个子节点 从而可以获得各个节点的值
List<BookType> bookList = booksType.getBook();
for( int i = 0; i < bookList.size();i++ ) { System.out.println("Book details " ); test.jaxb.BookType book =(test.jaxb.BookType) bookList.get(i); System.out.println("Item id: " + book.getItemId()); System.out.println("Book Name: " + book.getName().trim()); System.out.println("Book ISBN: " + book.getISBN()); System.out.println("Book Price: " + book.getPrice().trim()); System.out.println("Book category: " + book.getBookCategory()); System.out.println("Book promotion: " + book.getPromotion(). getDiscount().trim()); System.out.println("No of Authors " + book.getAuthors().getAuthorName().size()); BookType.AuthorsType authors = book.getAuthors(); for (int j = 0; j < authors.getAuthorName().size();j++) { String authorName = (String) authors.getAuthorName().get(j); System.out.println("Author Name " + authorName.trim()); } System.out.println(); }
效果 :
Book details Item id: 999 Book Name: Learning JAXB Book ISBN: 123445 Book Price: 34 $ Book category: other Book promotion: 10% on this book if purchased by March 2003 No of Authors 1 Author Name Jane Doe Book details Item id: 129 Book Name: Java Webservices today and Beyond Book ISBN: 522965 Book Price: 29 $ Book category: magazine Book promotion: Buy one get Learning webservices Part 1 free No of Authors 2 Author Name John Brown Author Name Peter T.