傳統(tǒng)方式下,我們都是通過dom4j或者jdom方式來解析xml,一般都是將整個xml解析成內(nèi)存中的document,再分層次遍歷document樹,這樣有以下幾個不好的地方,首先是占內(nèi)存,還有就是代碼死板,不能針對通用的xml進(jìn)行解析,但是Jaxb卻不一樣,可以針對任何類型的xml進(jìn)行解析,即使xml發(fā)生改變,可以只用該少量的代碼,而不用更改代碼邏輯,具體方法如下:
1,生成xsd
首先,我們按照現(xiàn)有的xml文件生成改文件對應(yīng)的xsd文件,方法是采用xsd.exe方式,這個exe文件由微軟提供,我們可以在我們本地找到這個文件,然后將xml文件放到exe文件相同的目錄下,比如我們的xml文件名為resource.xml,然后我們進(jìn)入命令行,然后到exe文件所在的路徑下,通過xsd resource.xml,即可生成對應(yīng)的resource.xsd,即為我們需要的xsd文件。
2,生成xsd中定義對應(yīng)的代碼
jdk提供了一個xjc.jar可以為我們將xsd轉(zhuǎn)換成對應(yīng)的代碼,方法如下:
xjc –d d:/ –p com.huawei.test resource.xsd上面的參數(shù)定義如下:-d 指xsd文件所在的路徑,-p指生成的代碼所在的包名.
3,將xml文件讀成內(nèi)存中的對象
假如,我們的resource.xml中定義了一個Customer ,然后我們就可以按照下面這種方式將xml讀成我們內(nèi)存中的Customer對象:
(1)marshal,將xml生成內(nèi)存對象:
public void marshalToObject(){ File file = new File("C://file1.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output PRetty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(customer, file); jaxbMarshaller.marshal(customer, System.out); }(2)Unmarshaller,將內(nèi)存中創(chuàng)建的對象生成xml文件:
public void UnmarshallerToXml(){ File file = new File("C://file.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file); System.out.println(customer); }
新聞熱點(diǎn)
疑難解答