xStream XML Conversion

Original: http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html

 

xStream framework

xStream can easily Java objects and xml document conversion, and you can modify a particular property and the node name, but also supports converting json; 

Front introduced json-lib this framework, Online Bowen: http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html

And Jackson this framework, Online Bowen: http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html 

They are the perfect support for JSON, but support for xml is not very good. Limiting description of Java objects to a certain extent, can not let xml fully reflect the description of Java objects. Here will introduce xStream perfect support for JSON, XML is. xStream is not only very friendly to XML conversion, but also provides annotation notes can complete description of the xml node property in the JavaBean. And also supports JSON, only need to provide relevant JSONDriver can complete the conversion.

Recommended: xml conversion using xStream framework; JSON conversion using Jackson framework.

1. Preparations 

1.1. Download jar package, and official resources 

xStream's jar Download: 

https://nexus.codehaus.org/content/repositories/releases/com/thoughtworks/xstream/xstream-distribution/1.3.1/xstream-distribution-1.3.1-bin.zip

The official example is full, official reference example: http://xstream.codehaus.org/tutorial.html 

Add xstream-1.3.1.jar file to the project, you can start work the following;

1.2. Need JavaBean

Birthday :

public class Birthday {
	private String birthday;

	public Birthday() {
	}

	public Birthday(String birthday) {
		this.birthday = birthday;
	}

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
}

Student :

public class Student {

	private int id;

	private String name;

	private String email;

	private String address;

	private Birthday birthday;

	// getter、setter

	public String toString() {
		return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
	}

}

ListBean:

import java.util.List;

public class ListBean {

	private String name;
	private List<Object> list;

	// getter、setter
}

2. Java into XML

2.1. JavaBean XML Conversion

import com.thoughtworks.xstream.XStream;

/**
 * Java对象和XML字符串的相互转换
 */
public class WriteBean2XML {
	private static XStream xstream = new XStream();

	public static void main(String[] args) {
		Student bean = new Student();
		bean.setAddress("china");
		bean.setEmail("[email protected]");
		bean.setId(1);
		bean.setName("jack");
		Birthday day = new Birthday();
		day.setBirthday("2010-11-22");
		bean.setBirthday(day);
		System.out.println(xstream.toXML(bean));
		System.out.println();
		
		// 类重命名
		// xstream.alias("account", Student.class);
		// xstream.alias("生日", Birthday.class);
		// xstream.aliasField("生日", Student.class, "birthday");
		// xstream.aliasField("生日", Birthday.class, "birthday");
		// fail(xstream.toXML(bean));
		// 属性重命名
		xstream.aliasField("邮件", Student.class, "email");
		// 包重命名
		xstream.aliasPackage("", "test2");
		System.out.println(xstream.toXML(bean));
	}
}

By toXML method XStream object can be completed Java objects to XML conversion, there are two methods toXML same signature method, we need to pass a stream. Then to complete the flow of information through an output xml.

Xml content to see the first results, is not the result and then modify or rename the document, as it is output. The second document is a document in rename package, email properties and also in rename class names can also be renamed. 

After the results are as follows: 

<test2.Student>
  <id>1</id>
  <name>jack</name>
  <email>[email protected]</email>
  <address>china</address>
  <birthday>
    <birthday>2010-11-22</birthday>
  </birthday>
</test2.Student>

<Student>
  <id>1</id>
  <name>jack</name>
  <邮件>[email protected]</邮件>
  <address>china</address>
  <birthday>
    <birthday>2010-11-22</birthday>
  </birthday>
</Student>

2.2. List collection to convert into xml document

import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;

/**
 * 将List集合转换成xml文档
 */
public class WriteList2XML {
	private static XStream xstream = new XStream();

	public static void main(String[] args) {
		try {
			ListBean listBean = new ListBean();
			listBean.setName("this is a List Collection");
			List<Object> list = new ArrayList<Object>();
			Student bean1 = new Student();
			bean1.setAddress("USA");
			bean1.setEmail("[email protected]");
			bean1.setId(2);
			bean1.setName("tom");
			Birthday day1 = new Birthday("2010-11-22");
			bean1.setBirthday(day1);
			list.add(bean1);
			Student bean2 = new Student();
			bean2.setAddress("china");
			bean2.setEmail("[email protected]");
			bean2.setId(2);
			bean2.setName("zhansan");
			Birthday day2 = new Birthday("2001-05-06");
			bean2.setBirthday(day2);
			list.add(bean2);
			list.add(bean2);
			listBean.setList(list);
			// 修改元素名称
			xstream.alias("beans", ListBean.class);
			xstream.alias("student", Student.class);
			// 将ListBean中的集合设置空元素,即不显示集合元素标签
			// xstream.addImplicitCollection(ListBean.class, "list");
			// 设置reference模型
			//xstream.setMode(XStream.NO_REFERENCES);//不引用
			xstream.setMode(XStream.ID_REFERENCES);// id引用
			// xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);//绝对路径引用
			// 将name设置为父类(Student)的元素的属性
			xstream.useAttributeFor(Student.class, "name");
			xstream.useAttributeFor(Birthday.class, "birthday");
			// 修改属性的name
			xstream.aliasAttribute("姓名", "name");
			xstream.aliasField("生日", Birthday.class, "birthday");
			System.out.println(xstream.toXML(listBean));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

After the results are as follows: 

<beans id="1">
  <name>this is a List Collection</name>
  <list id="2">
    <student id="3" 姓名="tom">
      <id>2</id>
      <email>[email protected]</email>
      <address>USA</address>
      <birthday id="4" 生日="2010-11-22"/>
    </student>
    <student id="5" 姓名="zhansan">
      <id>2</id>
      <email>[email protected]</email>
      <address>china</address>
      <birthday id="6" 生日="2001-05-06"/>
    </student>
    <student reference="5"/>
  </list>
</beans>

If not xstream.addImplicitCollection (ListBean.class, "list"); 

This set, there will be a wrapped Student List node node elements. Add addImplicitCollection can ignore this list node element. Then the above list node does not exist, it will only appear in beans element name, student xml elements of these two labels; 

setMode setting the same reference object, if no reference is provided XStream.NO_REFERENCES will output the same elements Student 2 minutes. If XStream.ID_REFERENCES that reference the same id attribute of the object, if it is XStream.XPATH_ABSOLUTE_REFERENCES reference, it will display xpath path. id uses cited above, <student reference = "3" /> The references that student id = 3, an element tag; 

useAttributeFor a node is set to the display attribute of the parent node, i.e. the specified class in the specified property, it is displayed in the attribute class element node. 

如:<student><name>hoojo</name></student> 

After setting this result is: <student name = "hoojo"> </ student> 

aliasAttribute is to modify the attribute name.

2.3. Annotation add annotations provided rename a JavaBean 

JavaBean code

import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;

@XStreamAlias("class")
public class Classes {

	// 设置属性显示
	@XStreamAsAttribute
	@XStreamAlias("名称")
	private String name;

	// 忽略
	@XStreamOmitField
	private int number;

	@XStreamImplicit(itemFieldName = "Students")
	private List<Student> students;

	@XStreamConverter(SingleValueCalendarConverter.class)
	private Calendar created = new GregorianCalendar();

	public Classes() {
	}

	public Classes(String name, Student... stu) {
		this.name = name;
		this.students = Arrays.asList(stu);
	}

	// getter、setter
}

This is a type SingleValueCalendarConverter.java converter

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class SingleValueCalendarConverter implements Converter {

	public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
		Calendar calendar = (Calendar) source;
		writer.setValue(String.valueOf(calendar.getTime().getTime()));
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(new Date(Long.parseLong(reader.getValue())));
		return calendar;
	}

	@SuppressWarnings("rawtypes")
	public boolean canConvert(Class type) {
		return type.equals(GregorianCalendar.class);
	}
}

Test code

import com.thoughtworks.xstream.XStream;

public class WriteList2XML4Annotation {
	private static XStream xstream = new XStream();

	public static void main(String[] args) {
		try {
			Student bean1 = new Student();
			bean1.setAddress("USA");
			bean1.setEmail("[email protected]");
			bean1.setId(2);
			bean1.setName("tom");
			Birthday day1 = new Birthday("2010-11-22");
			bean1.setBirthday(day1);
			Student bean2 = new Student();
			bean2.setAddress("china");
			bean2.setEmail("[email protected]");
			bean2.setId(2);
			bean2.setName("zhansan");
			Birthday day2 = new Birthday("2001-05-06");
			bean2.setBirthday(day2);
			Classes c = new Classes("一班", bean1, bean2);
			c.setNumber(2);
			// 对指定的类使用Annotation
			// xstream.processAnnotations(Classes.class);
			// 启用Annotation
			// xstream.autodetectAnnotations(true);
			xstream.alias("student", Student.class);
			System.out.println(xstream.toXML(c));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

When you enable annotation or to a particular class enables annotation, the above classes of this class will be effective. If the annotation is not enabled, the results are as follows:

<test2.Classes>
  <name>一班</name>
  <number>2</number>
  <students class="java.util.Arrays$ArrayList">
    <a class="student-array">
      <student>
        <id>2</id>
        <name>tom</name>
        <email>[email protected]</email>
        <address>USA</address>
        <birthday>
          <birthday>2010-11-22</birthday>
        </birthday>
      </student>
      <student>
        <id>2</id>
        <name>zhansan</name>
        <email>[email protected]</email>
        <address>china</address>
        <birthday>
          <birthday>2001-05-06</birthday>
        </birthday>
      </student>
    </a>
  </students>
  <created>
    <time>1413786635143</time>
    <timezone>Asia/Shanghai</timezone>
  </created>
</test2.Classes>

When you enable annotation after xstream.processAnnotations (Classes.class), as follows:

<class 名称="一班">
  <Students>
    <id>2</id>
    <name>tom</name>
    <email>[email protected]</email>
    <address>USA</address>
    <birthday>
      <birthday>2010-11-22</birthday>
    </birthday>
  </Students>
  <Students>
    <id>2</id>
    <name>zhansan</name>
    <email>[email protected]</email>
    <address>china</address>
    <birthday>
      <birthday>2001-05-06</birthday>
    </birthday>
  </Students>
  <created>1413786890887</created>
</class>

2.4. Map collection of converted xml document

import java.util.HashMap;
import java.util.Map;

import com.thoughtworks.xstream.XStream;

/**
 * Map集合转换xml文档
 */
public class writeMap2XML {
	private static XStream xstream = new XStream();

	public static void main(String[] args) {
		try {
			Student bean1 = new Student();
			bean1.setAddress("china");
			bean1.setEmail("[email protected]");
			bean1.setId(1);
			bean1.setName("tom");
			Birthday day = new Birthday("2010-11-22");
			bean1.setBirthday(day);

			Student bean2 = new Student();
			bean2.setAddress("china");
			bean2.setEmail("[email protected]");
			bean2.setId(2);
			bean2.setName("zhansan");
			Birthday day2 = new Birthday("2001-05-06");
			bean2.setBirthday(day2);

			Map<String, Student> map = new HashMap<String, Student>();
			map.put("No.1", bean1);// put
			map.put("No.2", bean2);// put
			xstream.alias("student", Student.class);
			xstream.alias("key", String.class);
			xstream.useAttributeFor(Student.class, "id");
			xstream.useAttributeFor("birthday", String.class);
			System.out.println(xstream.toXML(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

After the results are as follows:

<map>
  <entry>
    <key>No.1</key>
    <student id="1">
      <name>tom</name>
      <email>[email protected]</email>
      <address>china</address>
      <birthday birthday="2010-11-22"/>
    </student>
  </entry>
  <entry>
    <key>No.2</key>
    <student id="2">
      <name>zhansan</name>
      <email>[email protected]</email>
      <address>china</address>
      <birthday birthday="2001-05-06"/>
    </student>
  </entry>
</map>

2.5. Flow write XML output with OutStream

import java.io.ObjectOutputStream;

import com.thoughtworks.xstream.XStream;

/**
 * 用OutStream输出流写XML
 */
public class WriteXML4OutStream {
	private static XStream xstream = new XStream();
	private static ObjectOutputStream out = null;

	public static void main(String[] args) {
		try {
			Student bean = new Student();
			bean.setAddress("china");
			bean.setEmail("[email protected]");
			bean.setId(1);
			bean.setName("tom");
			Birthday day = new Birthday("2010-11-22");
			bean.setBirthday(day);
			
			out = xstream.createObjectOutputStream(System.out);
			Student stu = new Student();
			stu.setName("jack");
			Classes c = new Classes("一班", bean, stu);
			c.setNumber(2);
			out.writeObject(stu);
			out.writeObject(new Birthday("2010-05-33"));
			out.write(22);// byte
			out.writeBoolean(true);
			out.writeFloat(22.f);
			out.writeUTF("hello");
			
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

After using the output stream, may be accomplished by constructing xml stream object, even without JavaBean objects, you can use to build a complex flow xml document, the results are as follows:

<object-stream>
  <test2.Student>
    <id>0</id>
    <name>jack</name>
  </test2.Student>
  <test2.Birthday>
    <birthday>2010-05-33</birthday>
  </test2.Birthday>
  <byte>22</byte>
  <boolean>true</boolean>
  <float>22.0</float>
  <string>hello</string>
</object-stream>

3. XML content into Java objects

3.1. InputStream with transforming XML documents into java objects

import java.io.ObjectInputStream;
import java.io.StringReader;

import com.thoughtworks.xstream.XStream;

/**
 * 用InputStream将XML文档转换成java对象
 */
public class ReadXML4InputStream {
	private static XStream xstream = new XStream();

	public static void main(String[] args) {
		try {
			String s = "<object-stream><test2.Student><id>0</id><name>jack</name>"
					+ "</test2.Student><test2.Birthday><birthday>2010-05-33</birthday>"
					+ "</test2.Birthday><byte>22</byte><boolean>true</boolean><float>22.0</float>"
					+ "<string>hello</string></object-stream>";
			StringReader reader = new StringReader(s);
			ObjectInputStream in = xstream.createObjectInputStream(reader);
			Student stu = (Student) in.readObject();
			Birthday b = (Birthday) in.readObject();
			byte i = in.readByte();
			boolean bo = in.readBoolean();
			float f = in.readFloat();
			String str = in.readUTF();
			System.out.println(stu);
			System.out.println(b);
			System.out.println(i);
			System.out.println(bo);
			System.out.println(f);
			System.out.println(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

After reading, Java object conversion results were as follows:

jack#0#null#null#null
test2.Birthday@17590db
22
true
22.0
hello

XStream to JSON is also supported, but not recommended to use the Jar perform the conversion. Presented here do not.


Published 45 original articles · won praise 21 · views 660 000 +

Guess you like

Origin blog.csdn.net/yin_jw/article/details/40348315