java xml 转换

java --> xml
原理是用反射机制将对象中的属性映射出来,通过xml来排版
xml --> java
用sax解析每一行数据,调用反射将值放到对象中


用XStream来进行转换
XStream xstream = new XStream();
		xstream.alias("person", Person.class);

		Person person = new Person("XP", "male", 29);// 自己定义的构造函数
		person.setPhoneNumber(new PhoneNumber("027", "88386666"));

		String xml = xstream.toXML(person);
		System.out.println(xml);

		System.out.println("-------------");

		Person p2 = (Person) xstream.fromXML(xml);
		System.out.println(p2.getName());
		System.out.println(p2.getSex());
		System.out.println(p2.getPhoneNumber().getNumber());

		System.out.println("-------------");


public class Person {
	private String name;
	private String sex;
	private int age;
	private PhoneNumber phoneNumber;
}


public class PhoneNumber {
	private String code;
	private String number;
}



你可能感兴趣的:(java)