xml和实体对象相互转换 一步到位_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > xml和实体对象相互转换 一步到位

xml和实体对象相互转换 一步到位

 2012/9/8 11:52:13  crawler  程序员俱乐部  我要评论(0)
  • 摘要:用Xstream完成xml与对象之间的相互转换,我在xstream包的基础上简单的封装了一下:如以下xml:<?xmlversion="1.0"encoding="UTF-8"?><html><body><divid="div1"name="div"/><formaction="saveForm.asp"method="post"><h1>请输入您的联系信息:</h1><lable>名字:<
  • 标签:XML

用Xstream完成xml与对象之间的相互转换,我在xstream包的基础上简单的封装了一下:

如以下xml:

<?xml version="1.0" encoding="UTF-8"?>
<html>
  <body>
    <div id="div1" name="div"/>
    <form action="saveForm.asp" method="post">
      <h1>请输入您的联系信息:</h1>
      <lable>名字:</lable>
      <p>
        <input type="submit" id="btn_sub" name="btn_sub" value="Submit"/>
        <input type="reset" id="btn_res" name="btn_res" value="Reset"/>
      </p>
    </form>
  </body>
</html>

?想快速转换成对象。

?

第一步将xml分解成不同的对象如下,HtmlBean 为主体对象:

?<html>标签:?

@XStreamAlias("html")
public class HtmlBean implements BaseConverterBean {
	private HtmlBody body;

	public HtmlBody getBody() {
		return body;
	}

	public void setBody(HtmlBody body) {
		this.body = body;
	}

}

?

<body>标签:

@XStreamAlias("body")
public class HtmlBody implements BaseConverterBean {
	private HtmlDiv div;
	private HtmlForm form;

	public HtmlForm getForm() {
		return form;
	}

	public void setForm(HtmlForm form) {
		this.form = form;
	}

	public HtmlDiv getDiv() {
		return div;
	}

	public void setDiv(HtmlDiv div) {
		this.div = div;
	}

}

?<div>标签:

@XStreamAlias("div")
public class HtmlDiv implements BaseConverterBean {
	@XStreamAsAttribute
	private String id;
	@XStreamAsAttribute
	private String name;

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

}

?

<form>标签:

@XStreamAlias("form")
public class HtmlForm implements BaseConverterBean {
	@XStreamAsAttribute
	private String action;
	@XStreamAsAttribute
	private String method;
	private String h1;
	private String lable;
	private HtmlP p;

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public String getMethod() {
		return method;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public String getH1() {
		return h1;
	}

	public void setH1(String h1) {
		this.h1 = h1;
	}

	public String getLable() {
		return lable;
	}

	public void setLable(String lable) {
		this.lable = lable;
	}

	public HtmlP getP() {
		return p;
	}

	public void setP(HtmlP p) {
		this.p = p;
	}

}

?<p>标签:

@XStreamAlias("p")
public class HtmlP implements BaseConverterBean {
	
	@XStreamImplicit
	private List<HtmlInput> input;

	public List<HtmlInput> getInput() {
		return input;
	}

	public void setInput(List<HtmlInput> input) {
		this.input = input;
	}

}

?

<input>标签:

@XStreamAlias("input")
public class HtmlInput implements BaseConverterBean {
	@XStreamAsAttribute
	private String type;
	@XStreamAsAttribute
	private String id;
	@XStreamAsAttribute
	private String name;
	@XStreamAsAttribute
	private String value;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

}

?

第二步:利用xstream将xml文件转换为对象HtmlBean :

public class XMLToBeanConverterTest {

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testToBean() {
		HtmlBean bean = null;
		XStream xstream = XstreamUtil.getDriverInstace();
		String xml = getResourceFileContent(XMLToBeanConverterTest.class, "html.xml");
		if(xml!=null && !"".equals(xml)){
			bean = (HtmlBean)ConverterFactory.getXMLToBeanConverterInstance(xml).stringToBean(xstream, HtmlBean.class, true);
		}
		String divid = bean.getBody().getDiv().getId();
		String expected = "div1";
		assertEquals(expected, divid);
	}
	
    @SuppressWarnings("unchecked")
	public static String getResourceFileContent(Class c,String name){
    	StringBuffer sb = new StringBuffer();
    	try {
    		InputStream input = c.getClassLoader().getResourceAsStream(name);
    		BufferedReader reader = new BufferedReader(new InputStreamReader(input,"UTF-8"));
    		String line = null;
    		while ((line = reader.readLine()) != null) {
    			sb.append(line);
    		}
    		reader.close();
    		input.close();
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	return sb.toString();
    }
}

?

ConverterFactory:

/**
 * 转换器工厂
 * 
 * @author crawler
 * 
 */
public class ConverterFactory {
	/**
	 * 获得BeanToXMLConverter实例化对象
	 * 
	 * @param bean  实体Bean对象
	 *           
	 * @return BeanToXMLConverter 实例化对象
	 */
	public static XMLConverter getBeanToXMLConverterInstance(BaseConverterBean bean) {
		return new BeanToXMLConverter(bean);
	}
	
	public static BeanConverter getXMLToBeanConverterInstance(String xml) {
		return new XMLToBeanConverter(xml);
	}
}

?XMLToBeanConverter:

/**
 * xml转换为对应的实体bean对象
 * 
 * @author crawler
 * 
 */
public class XMLToBeanConverter implements BeanConverter {
	private String xml;
	public XMLToBeanConverter(String xml){
		this.xml = xml;
	}
	@SuppressWarnings("unchecked")
	public BaseConverterBean stringToBean(XStream xstream,Class type,boolean isAttribute) {
		if(isAttribute){
			xstream.processAnnotations(type);
		}
		return (BaseConverterBean)xstream.fromXML(xml);
	}
}

??

第三步:将bean对象转换成xml:

public class BeanToXMLConverterTest {
	
	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testToXml() {
		HtmlBean bean = new HtmlBean();
		HtmlBody body = new HtmlBody();
		HtmlDiv div = new HtmlDiv();
		HtmlForm form = new HtmlForm();
		HtmlP p = new HtmlP();
		List<HtmlInput> inputs = new ArrayList<HtmlInput>();
		
		HtmlInput input = new HtmlInput();
		input.setId("btn_sub");
		input.setType("submit");
		input.setName("btn_sub");
		input.setValue("Submit");
		
		HtmlInput input2 = new HtmlInput();
		input2.setId("btn_res");
		input2.setType("reset");
		input2.setName("btn_res");
		input2.setValue("Reset");
		
		inputs.add(input);
		inputs.add(input2);
		
		p.setInput(inputs);
		
		div.setId("div1");
		div.setName("div");
		
		form.setAction("saveForm.asp");
		form.setH1("请输入您的联系信息:");
		form.setLable("名字:");
		form.setMethod("post");
		form.setP(p);
		
		body.setDiv(div);
		body.setForm(form);
		
		bean.setBody(body);
		
		XMLConverter converter = ConverterFactory.getBeanToXMLConverterInstance(bean);
		XStream xstream = XstreamUtil.getInstance();
		// 将对象转换为xml文件
		String xml = converter.toXml(xstream, bean.getClass(), true);
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(xml);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		if(doc!=null){
			xml = doc.asXML();
		}
		System.out.println(xml);		
	}

}

?

BeanToXMLConverter:

/**
 * 将bean对象转换为xml形式的转换器
 * 
 * @author crawler
 * 
 */
public class BeanToXMLConverter implements XMLConverter {
	private BaseConverterBean bean;

	public BeanToXMLConverter(BaseConverterBean bean) {
		this.bean = bean;
	}

	@SuppressWarnings("unchecked")
	public String toXml(XStream xstream,Class type,boolean isAttribute) {
		if(isAttribute){
			xstream.processAnnotations(type);
		}
		return xstream.toXML(bean);
	}
}

?

打印结果:

<?xml version="1.0" encoding="UTF-8"?>
<html>
  <body>
    <div id="div1" name="div"/>
    <form action="saveForm.asp" method="post">
      <h1>请输入您的联系信息:</h1>
      <lable>名字:</lable>
      <p>
        <input type="submit" id="btn_sub" name="btn_sub" value="Submit"/>
        <input type="reset" id="btn_res" name="btn_res" value="Reset"/>
      </p>
    </form>
  </body>
</html>

?

与顶部的xml完全一致。这样就完成了相互的转换很方便。

如果需要可以下载附件我贴上了我的Myeclipse工程,有对应的测试类和源码。

  • XstreamConverter.zip (699.1 KB)
  • 下载次数: 50
发表评论
用户名: 匿名