微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐