`

文字水平滚动

    博客分类:
  • jsp
XML 
阅读更多

前一阵子写了一篇JAXB的运用,其中讲了如何用JAXB生成XML Schame文件对应的类,也给出一个通过运用JAXB生成的类来组织XML文件,最后输出的例子!
这两天对JAXB进行了更深入的理解,发现既然可以用它来生成XML文件,为何不能读取其中的结点,然后获取其中的信息呢!下面给出对上次写生成的test.xml文件的读取的方法:

/**//*
*createbyisle_t2008-04-30
*读取用jaxb根据xsd,生成的xml文件
*/

importjava.io.FileInputStream;
importjava.io.IOException;

importjava.util.Iterator;
importjava.util.List;

importjavax.xml.bind.JAXBContext;
importjavax.xml.bind.JAXBElement;
importjavax.xml.bind.JAXBException;
importjavax.xml.bind.Unmarshaller;

importprimer.po.Items;
importprimer.po.PurchaseOrderType;
importprimer.po.USAddress;


publicclassMainOut{

publicstaticvoidmain(String[]args){
try{
//createaJAXBContext
JAXBContextjc=JAXBContext.newInstance("primer.po");

Unmarshalleru
=jc.createUnmarshaller();

JAXBElementcustomerE
=(JAXBElement)u.unmarshal(newFileInputStream(
"test.xml"));
//读取出根结点PurchaseOrderType
PurchaseOrderTypebo=(PurchaseOrderType)customerE.getValue();
//获取子结点USAddress
USAddressaddress=bo.getBillTo();
//获取name值
Stringaddressname=address.getName();

System.out.println(addressname);

//获取另一子结点Items
Itemsitem=bo.getItems();

List
<Items.Item>itemList=item.getItem();

Iteratorit
=itemList.iterator();

while(it.hasNext()){
Items.Itemii
=(Items.Item)it.next();
System.out.println(ii.getPartNum()
+""+ii.getProductName()+""+ii.getQuantity()+""+ii.getUSPrice()+""+ii.getShipDate()+""+ii.getComment());
}


}
catch(JAXBExceptionje){
je.printStackTrace();
}
catch(IOExceptionioe){
ioe.printStackTrace();
}

}


}

如果我上次写的那篇JAXB的运用看过的话,可以更好的理解上面写的,在这里我没有读取每一个节点,只是将其中典型的列举出来了,如果你对JAXB不熟的话,要好好研究,还得多看看其它资料。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics