XStream中使用annotation处理attribute

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

 

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

javabean的attribute使用@XStreamAsAttribute来定义,

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

 

XML文件如下:

 

<?xml version="1.0" encoding="UTF-8"?>
	<!-- 接口定义-->
<interfaceDefine>
	<osUDPairCollectReq>
		<version>1.0.0</version>
		<providerSID>00600001</providerSID>
		<providerEID>0005</providerEID>
		<providerECID>0005.01</providerECID>
		<providerIFName>osUDPairCollect</providerIFName>
		<callingType>01</callingType>
	</osUDPairCollectReq>
	<!—测试使用attribute -->
	<deviceCaps>
		<services>
			<service name="BMS">
				<items>
					<item id="160" yes="YES" no="NO" />
				</items>
			</service>
		</services>
	</deviceCaps>
</interfaceDefine>

 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<Item> 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);
	}
}

你可能感兴趣的:(xml)