爱程序网

Jaxb解析XML

来源: 阅读:

    传统方式下,我们都是通过dom4j或者jdom方式来解析xml,一般都是将整个xml解析成内存中的document,再分层次遍历document树,这样有以下几个不好的地方,首先是占内存,还有就是代码死板,不能针对通用的xml进行解析,但是Jaxb却不一样,可以针对任何类型的xml进行解析,即使xml发生改变,可以只用该少量的代码,而不用更改代码逻辑,具体方法如下:

1,生成xsd

首先,我们按照现有的xml文件生成改文件对应的xsd文件,方法是采用xsd.exe方式,这个exe文件由微软提供,我们可以在我们本地找到这个文件,然后将xml文件放到exe文件相同的目录下,比如我们的xml文件名为resource.xml,然后我们进入命令行,然后到exe文件所在的路径下,通过xsd resource.xml,即可生成对应的resource.xsd,即为我们需要的xsd文件。

 

2,生成xsd中定义对应的代码

jdk提供了一个xjc.jar可以为我们将xsd转换成对应的代码,方法如下:

xjc –d d:\ –p com.huawei.test resource.xsd

上面的参数定义如下:-d 指xsd文件所在的路径,-p指生成的代码所在的包名.

 

3,将xml文件读成内存中的对象

假如,我们的resource.xml中定义了一个Customer ,然后我们就可以按照下面这种方式将xml读成我们内存中的Customer对象:

(1)marshal,将xml生成内存对象:

 

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,将内存中创建的对象生成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);  
}

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助