JAXB的使用

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.

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值