加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Webservice_08_JAXB处理java和xml

发布时间:2020-12-17 00:12:22 所属栏目:安全 来源:网络整理
导读:非常感谢 孙浩 老师。 Coder.java package cn.lichen.bean;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class Coder {private int coderId;private String name;private String position;private Item item;public Coder() {//

非常感谢孙浩老师。

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()+"tt"+coder.getItem().getName());
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读