天天看点

实体类与XML报文相互转化

1、注入依赖

<dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.12</version>
        </dependency>
           

2、测试实体类(具体开发需要的实体类 根据需求自行编写)

ResultInfo :

import java.util.List;
public class ResultInfo {
	
	private String test;
	
	private String abc;
	
	private List<User> Users;

	public String getTest() {
		return test;
	}
	public void setTest(String test) {
		this.test = test;
	}
	public String getAbc() {
		return abc;
	}
	public void setAbc(String abc) {
		this.abc = abc;
	}
	public List<User> getUsers() {
		return Users;
	}
	public void setUsers(List<User> users) {
		this.Users = users;
	}
}

           

User:

public class User {
	private String name;
	
	private String age;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
}

           

3、将实体类转换为XML报文

package result;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.DateConverter;

public class Main {
	public static void main(String[] args) throws JAXBException {
		ResultInfo resultInfo=new ResultInfo();
		List<User> users=new ArrayList<User>();
		User user1=new User();
		User user2=new User();
		user1.setName("user1");
		user1.setAge("1");
		user2.setName("user2");
		user2.setAge("2");
		users.add(user1);
		users.add(user2);
		resultInfo.setTest("test");
		resultInfo.setAbc("abc");
		resultInfo.setUsers(users);
		XStream xStream=new XStream();
		xStream.setClassLoader(ResultInfo.class.getClassLoader());
		xStream.allowTypes(new Class[] {ResultInfo.class});
		xStream.alias("ResultInfo",ResultInfo.class);
		xStream.alias("User",User.class); // 去除包名
		xStream.registerConverter(new DateConverter());
		xStream.processAnnotations(new Class[] {ResultInfo.class});
	    String result=xStream.toXML(resultInfo);
     	System.out.println(result);
	}
}
           

输出结果:

<ResultInfo>
  <test>test</test>
  <abc>abc</abc>
  <Users>
    <User>
      <name>user1</name>
      <age>1</age>
    </User>
    <User>
      <name>user2</name>
      <age>2</age>
    </User>
  </Users>
</ResultInfo>
           

4、将XML报文转换为实体类

XStream xStream=new XStream();
		xStream.setClassLoader(ResultInfo.class.getClassLoader());
		xStream.alias("ResultInfo",ResultInfo.class);
		xStream.alias("User",User.class); // 去除包名
		// result 是第三步所生成的xml报文
		ResultInfo resultInfo2=(ResultInfo) xStream.fromXML(result);