Webservice_08_JAXB处理java和xml

非常感谢孙浩老师。

Coder.java

package cn.lichen.bean;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Coder {
	private int coderId;
	private String name;
	private String position;
	private Item item;
	
	public Coder() {
		// TODO Auto-generated constructor stub
	}
	
	public Coder(int coderId, String name, String position, Item item) {
		super();
		this.coderId = coderId;
		this.name = name;
		this.position = position;
		this.item = item;
	}

	public int getCoderId() {
		return coderId;
	}
	public String getName() {
		return name;
	}
	public String getPosition() {
		return position;
	}
	public void setCoderId(int coderId) {
		this.coderId = coderId;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setPosition(String position) {
		this.position = position;
	}
	public Item getItem() {
		return item;
	}
	public void setItem(Item item) {
		this.item = item;
	}
}

 

Item.java

package cn.lichen.bean;

public class Item {

	private int itemId;
	private String name;
	public Item() {
		// TODO Auto-generated constructor stub
	}
	
	public Item(int itemId, String name) {
		super();
		this.itemId = itemId;
		this.name = name;
	}

	public int getItemId() {
		return itemId;
	}
	public String getName() {
		return name;
	}
	public void setItemId(int itemId) {
		this.itemId = itemId;
	}
	public void setName(String name) {
		this.name = name;
	}
}


Java转为Xml:

@Test
	public void test1() {
		try {
			JAXBContext context = JAXBContext.newInstance(Coder.class);
			Marshaller marshaller = context.createMarshaller();
			Coder coder = new Coder(1, "lichen", "boss", new Item(1, "it"));
			marshaller.marshal(coder, System.out);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


 

 

Xml转为Java:

@Test
	public void test2() {
		try {
			String xml="<?xml version='1.0' encoding='UTF-8' standalone='yes'?><coder><coderId>1</coderId><item><itemId>1</itemId><name>it</name></item><name>lichen</name><position>boss</position></coder>";
			JAXBContext context = JAXBContext.newInstance(Coder.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			Coder coder = (Coder) unmarshaller.unmarshal(new StringReader(xml));
			System.out.println(coder.getName()+"\t\t"+coder.getItem().getName());
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值