XStream中使用annotation处理attribute

原先以为XStream不支持attribute。最近发现v1.3以后是支持的,使用annotation来定义,而且因为一直在用XStream,就不改成jaxb2.1了。

 

看见网上介绍得不多,贴一下源码,以供参考。

javabean的attribute使用@XStreamAsAttribute来定义,

同时需要调用 XStream.processAnnotations(YourClass.class);

 

XML文件如下:

 


	

	
		1.0.0
		00600001
		0005
		0005.01
		osUDPairCollect
		01
	
	
	
		
			
				
					
				
			
		
	

 JavaBean如下:

 

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

@XStreamAlias("interfaceDefine")
public class InterfaceDefine {
	/**
	 *测试的子类
	 */
	public static class OsRequestHeader {
		public String version, providerSID, providerEID, providerECID,
				providerIFName, callingType;
	}

	public static class DeviceCaps {
		public Service[] services;

		@XStreamAlias("service")
		public static class Service {
			@XStreamAsAttribute
			public String name;
			public Set items;
		}

		@XStreamAlias("item")
		public static class Item {
			@XStreamAsAttribute
			public Integer id;
			@XStreamAsAttribute
			public String yes = "YES";
			@XStreamAsAttribute
			public String no = "NO";
		}
	}

	/**
	 * 操作接口
	 */
	public OsRequestHeader osUDPairCollectReq;

	 

	public DeviceCaps deviceCaps;


        /*
        * 将对象转换成XML的实现
        */
	@Override
	public String toString() {
		XStream xs = new XStream();
		xs.processAnnotations(InterfaceDefine.class);
		return xs.toXML(this);
	}
}

你可能感兴趣的:(javase)