jaxb 从xml到java_JAXB XML到java object的转换

JAXB是Java Architecture for XML Binding的缩写。使用JAXB注解将Java对象转换成XML文件。在这篇教程中,我们将会展示如何使用JAXB来做以下事情:

1. marshall 将java对象转化成xml文件

2. unmarshalling 将xml内容转换成java对象

JAXB 注解(Annotation)

如果一个对象需要被转换成XML文件,或者从XML文件中生成,该对象需要用JAXB注解来标注。这些注解光凭名字就知道是什么意思了。具体可参考官网:jaxb guide

packagecom.jaxb.core;importjavax.xml.bind.annotation.XmlAttribute;importjavax.xml.bind.annotation.XmlElement;importjavax.xml.bind.annotation.XmlRootElement;

@XmlRootElementpublic classCustomer {

String name;intage;intid;publicString getName() {returnname;

}

@XmlElementpublic voidsetName(String name) {this.name =name;

}public intgetAge() {returnage;

}

@XmlElementpublic void setAge(intage) {this.age =age;

}public intgetId() {returnid;

}

@XmlAttributepublic void setId(intid) {this.id =id;

}

}

对象转换成XML

JAXB marshalling例子,将customer对象转换成XML文件。jaxbMarshaller.marshal()包含了许多重载方法,哪个输出符合你的要求就选择哪个方法。

packagecom.jaxb.core;importjava.io.File;importjavax.xml.bind.JAXBContext;importjavax.xml.bind.JAXBException;importjavax.xml.bind.Marshaller;public classJAXBExample {public static voidmain(String[] args) {

Customer customer= newCustomer();

customer.setId(100);

customer.setName("benson");

customer.setAge(23);try{

File file= new File("C:\\file.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);

}catch(JAXBException e) {

e.printStackTrace();

}

}

}

输出:

23

benson

XML转换成对象:

JAXB unmarshalling例子,将XML文件内容转换成customer对象。jaxbMarshaller.unmarshal()包含了许多重载方法,哪个适合你的输出,你就选择哪个方法。

package com.jaxb.core;

import java.io.File;

import javax.xml.bind.JAXBContext;

import javax.xml.bind.JAXBException;

import javax.xml.bind.Unmarshaller;

public class JAXBExample {

public static void main(String[] args) {

try {

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);

} catch (JAXBException e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值