码迷,mamicode.com
首页 > 其他好文 > 详细

Xstream 简单入门

时间:2016-05-08 01:17:34      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

参考了些资料:

在没有任何设置默认情况下,

java到xml的映射,
是java成员名对应xml的元素名,
java类的全名对应xml根元素的名字,
而实际中,往往是xml和java类都有了,要完成相互转换,必须进行别名映射。
 
别名配置包含三种情况:
1、类别名,用alias(String name, Class type)。
2、类成员别名,用aliasField(String alias, Class definedIn, String fieldName)

3、类成员作为属性别名,用 aliasAttribute(Class definedIn, String attributeName, String alias),单独命名没有意义,

还要通过useAttributeFor(Class definedIn, String fieldName) 应用到某个类上。


addImplicitCollection(Class ownerType, String fieldName),去掉集合类型生成xml的父节点。



一、建实体类

//设置类的别名
@XStreamAlias("person")
public class Person {
	//将name设置为XML person 元素的 attribute   
//	@XStreamAsAttribute()   
//	@XStreamAlias("username")
	private String name;
	
	

	private int age;
	
	  //将此字段名在XML中去掉   
//	@XStreamImplicit()   
	private List<Address> addressList = new ArrayList<Address>();

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public List<Address> getAddressList() {
		return addressList;
	}

	public void setAddressList(List<Address> addressList) {
		this.addressList = addressList;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", addressList="
				+ addressList + "]";
	}

	
}

@XStreamAlias("address")
public class Address {
	private String street;
	private int houseNo;

	
	
	public Address() {
		super();
	}

	public Address(String street, int houseNo) {
		super();
		this.street = street;
		this.houseNo = houseNo;
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public int getHouseNo() {
		return houseNo;
	}

	public void setHouseNo(int houseNo) {
		this.houseNo = houseNo;
	}

	@Override
	public String toString() {
		return "Address [street=" + street + ", houseNo=" + houseNo + "]";
	}

}

二、测试

package com.demo.stream;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;

/*
 * 使用的jar包:
 * xmlpull-1.1.3.1.jar
 * xpp3_min-1.1.4c.jar
 * xstream-1.4.8.jar
 * 
 * 个人建议:使用注解
 * 
 * 这样进行相互转换时就很方便了,不用手写过多的配置
 */
public class StreamDemo {
	
	
	//跟生成xml的设置保持一致就可以了
	public static void xmlToBean(String xml) {
		XStream xStream=new XStream();
//		stream.alias("person1", Person.class);//注解已经配置,不需要
//      stream.alias("address1", Address.class);
//		xStream.aliasField("username", Person.class, "name");
		
		 xStream.addImplicitCollection(Person.class, "addressList");
		xStream.setMode(XStream.NO_REFERENCES);
//		 xs.useAttributeFor(Person.class, "name");
		xStream.addImplicitCollection(Person.class, "addressList");
		
		xStream.processAnnotations(new Class[]{Person.class,Address.class});
		Person person = (Person)xStream.fromXML(xml);
		System.out.println(person);
		
	}
	
	public static void xmlToBean(File xmlFile) {
		XStream xStream=new XStream();
//		stream.alias("person1", Person.class);//注解已经配置,不需要
//      stream.alias("address1", Address.class);
//		xStream.aliasField("username", Person.class, "name");
		
	    xStream.addImplicitCollection(Person.class, "addressList");
		xStream.setMode(XStream.NO_REFERENCES);
//		 xs.useAttributeFor(Person.class, "name");
		xStream.addImplicitCollection(Person.class, "addressList");
		
		xStream.processAnnotations(new Class[]{Person.class,Address.class});
		Person person = (Person)xStream.fromXML(xmlFile);
		System.out.println(person);
	}
	
	
	private static String beanToXml() throws FileNotFoundException {
		 Person person=new Person();
		 
		 person.setName("张三");
		 person.setAge(23);
		 
		 List<Address> list=new ArrayList<Address>();
		 list.add(new Address("临沂路8弄", 1801));
		 list.add(new Address("漕河", 1900));
		 person.setAddressList(list);
		 
         XStream stream=new XStream();
         
         //设置别名,如果注解已经设置了,此时在这里的设置别名将无效
         //如果没有注解配置,那么这里的设置别名将有效啦
         //如果都不设置,默认是全类名,比如com.demo.stream.Address
//         stream.alias("person1", Person.class);
//         stream.alias("address1", Address.class);
         //还可以设置字段的别名 
//        stream.aliasField("username", Person.class, "name");
         
         //不引用,意思大概就是不生成ID属性
         stream.setMode(XStream.NO_REFERENCES);
         //会自动给person加个id属性
//         stream.setMode(XStream.ID_REFERENCES);
         
         
         //去掉集合类型生成xml的父节点
         //作用等同注解:@XStreamImplicit()   
         stream.addImplicitCollection(Person.class, "addressList");
         
         //将name字段作为Person的属性
         //作用等同注解@XStreamAsAttribute()   
//         stream.useAttributeFor(Person.class, "name");
         
       
         
//       注册使用了注解的Person类
         stream.processAnnotations(new Class[]{Person.class,Address.class});

         //转换为xml(默认格式化)
         String xml=stream.toXML(person);
         
         System.out.println(xml);
         return xml;
	}
   
	
       //将xml字符串写进文件
	private static void creatXMlFile(File file) throws IOException {
		 String xml=beanToXml();
		 String xmlContent="<?xml version=\"1.0\" encoding=\"GBK\"?>\n";
		 if (!file.exists()) {
			file.getParentFile().mkdirs();
//			file.createNewFile();
		 }
		 xmlContent+=xml;
		 //可以将xml字符串写入文件,要创建新文件,必须保证其父路径存在哦,单级目录自动创建文件
         PrintWriter pw=new PrintWriter(file);
         pw.write(xmlContent);
         pw.close();
         
         
         //如果要实现追加
     //  BufferedWriter bw=new BufferedWriter(new FileWriter(file ,true));
         //那么此时必须保证xml头部申明只能一次 
		/* if (file.length()==0) {
			 xmlContent+=xml;
		 }else{
			 xmlContent=xml;
		 }*/
         
	}
	
	
	public static void main(String[] args) throws IOException {
//	    String xml=	beanToXml();
	    
	    File file=new File("D:/测试数据xml/1/test.xml");
//	    creatXMlFile(file);
//		xmlToBean(xml);
	    //读取xml时,会自动寻找对应字段,跟顺序没有关系
	    xmlToBean(file);
	}
}




3.附加方法,将xml变成一行输出(webservcie测试可以用到)

public static String oneLine(File  file) throws FileNotFoundException {
        if (!file.exists()) {
			System.err.println("源文件不存在!");
			throw new  RuntimeException();
		}
        Scanner in=new Scanner(file);
        StringBuilder builder=new StringBuilder("");
        while(in.hasNext()){
        	builder.append(in.nextLine().trim());
        }
        
        System.out.println(builder.toString());
        
        return   builder.toString();
	}


Xstream 简单入门

标签:

原文地址:http://blog.csdn.net/u011165335/article/details/51340846

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!