首页>>程序代码>>XStream生成xml时将元素标签首字母转大写
XStream生成xml时将元素标签首字母转大写
来源: http://sunjun041640.blog.163.com 时间: 2015-01-02 23:10:20


import java.io.StringWriter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.mapper.Mapper;
import com.thoughtworks.xstream.mapper.MapperWrapper;
/**
* 生成/解析xml
* @author sunjun
*/
public class XmlUtil {
//这里xstream对象作为共享的全局变量,所以必须是线程安全的,XStream类的文档注释也说了是线程安全的,但前提条件是不使用注解:The XStream instance is thread-safe. That is, once the XStream instance has been created and configured, it may be shared across multiple threads allowing objects to be serialized/deserialized concurrently. Note, that this only applies if annotations are not auto-detected on -the-fly.
private static final XStream xs = new XStream(new DomDriver()) {
@Override
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new MyMapperWrapper(next);
}
};
//xs.aliasSystemAttribute(null, "class");
//如果一个类的属性是个父类,而构造这个类对象时,用的是子类,那么生成xml时,会生成这样的:<LCCont class="com.xxx.child.LCCont">,如果不想要这个class属性,那么就加上上面这句话
/**
* 对象转换成xml字符串
*
* @param object
* @return
*/
public static String toXML(Object object) {
StringWriter str = new StringWriter();
xs.toXML(object, str);
return str.toString();
}
/**
* xml字符串转换成对象
*
* @param clazz
* @param xml
* @return
*/
public static <T> T toObject(Class<T> clazz, String xml) {
return (T) xs.fromXML(xml);
}
/**
* 生成/解析xml时转换首字母大小写
*
* @author sunjun
*/
private static class MyMapperWrapper extends MapperWrapper {
public MyMapperWrapper(Mapper wrapped) {
super(wrapped);
}
public String serializedMember(Class type, String memberName) {
// object -> xml 首字母转大写
if (StringUtils.isNotBlank(memberName)) {
memberName = memberName.substring(0, 1).toUpperCase()
+ memberName.substring(1);
}
return super.serializedMember(type, memberName);
}
public String realMember(Class type, String serialized) {
// xml -> object 首字母转小写
if (StringUtils.isNotBlank(serialized)) {
serialized = serialized.substring(0, 1).toLowerCase()
+ serialized.substring(1);
}
return super.realMember(type, serialized);
}
}
public static void main(String[] args) {
User user = new User();
user.username = "a";
user.password = "b";
System.out.println(toXML(user));
}
}
class User {
String username, password;
}
运行:
<com.xxx.User>
<Username>a</Username>
<Password>b</Password>
</User>
pom.xml
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.2</version>
</dependency>

本页地址:http://www.easytd.com/chengxudaima/d_14120110430.html

上一篇:Struts2.1.6+jquery+json中出现的问题 下一篇:Spring3中用注解直接注入properties中的值