JAXB 简单Demo

jaxb.JaxbDemo

package jaxb;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import pojo.People;

public class JaxbDemo {
// 编组数据
public static void marshalData() throws JAXBException, IOException {
JAXBContext context = JAXBContext.newInstance(People.class);

Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "gb2312");// 编码格式
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
// 是否省略xml头信息(<?xml version="1.0" encoding="gb2312" standalone="yes"?>)
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);

People people = new People();

people.setLogo("=====");

people.setId(1);

people.setName("son");

People father = new People();

father.setId(2);

father.setName("father");

people.setFather(father);

FileOutputStream os = new FileOutputStream("People.xml");

marshaller.marshal(people, os);

os.close();
}

// 解组数据
public static void unmarshalData() throws JAXBException, FileNotFoundException {
JAXBContext context = JAXBContext.newInstance(People.class);

Unmarshaller unmarshaller = context.createUnmarshaller();

People p = (People) unmarshaller.unmarshal(new FileInputStream("People.xml"));

System.out.println(p.getId() + " : " + p.getName());
}
}

pojo.AbstractPeople
package pojo;

public class AbstractPeople {
private String logo;

public String getLogo() {
return logo;
}

public void setLogo(String logo) {
this.logo = logo;
}
}

pojo.People
package pojo;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "People")
@XmlAccessorType(XmlAccessType.FIELD)
public class People extends AbstractPeople{
private int id;

private String name;

private People father;

public People() {
}

public People(int id, String name) {
this.id = id;
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public People getFather() {
return father;
}

public void setFather(People father) {
this.father = father;
}

}

People.xml

<?xml version="1.0" encoding="gb2312" standalone="yes"?>
<People>
<logo>=====</logo>
<id>1</id>
<name>son</name>
<father>
<id>2</id>
<name>father</name>
</father>
</People>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值