用XStream转换复杂XML

针对标签里面直接使用值的xml,比如

 <IDS>
      <ID>1234534</ID>
      <ID>1111111111</ID>
    </IDS>

 

还有节点既有属性又有值的xml,比如

<INPUT>
  <RAW_SQL TYPE="PERSON">select id from person</RAW_SQL>
</INPUT>

需要一个转换器来转换,转换器代码如下:

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.zhhy.server.beans.RawSQL;

public class RawSQLConverter implements Converter {

 @SuppressWarnings("rawtypes")
 public boolean canConvert(Class clazz) {
  return clazz.equals(RawSQL.class);
 }

 public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext acontext) {
  RawSQL rawSQL = (RawSQL) value;
  if (rawSQL != null) {
   if (null != rawSQL.getType()) {
    writer.addAttribute("TYPE", rawSQL.getType());
   }
   writer.setValue(rawSQL.getRawSql() == null ? "" : rawSQL.getRawSql());
  }

 }

 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext arg1) {
  RawSQL rawSql = new RawSQL();
  String type = reader.getAttribute("TYPE");
  rawSql.setType(type);

  String value = reader.getValue();

  rawSql.setRawSql(value);

  return rawSql;

 }

}
类的annotation配置如下:

@XStreamAlias("RAW_SQL")
@XStreamConverter(RawSQLConverter.class)
public class RawSQL {
 @XStreamAsAttribute
 @XStreamAlias("TYPE")
 private String type;

 private String rawSql;

 下面省略了getter和setter方法
}

 

 

后记:(2012-05-18日添加)

如果对象中定义的类型与实际类型不一致,比如定义的是Object类型,但是实际初始化的对象是其他类型,转换出来的xml文件都会加上class="实际类型"属性,举例:<PERSON class="PERSON">...</PERSON>

有两种方法去掉这个属性

1, xstream.alias("field name", Interface.class, ActualClassToUse.class);
2, xstream.aliasSystemAttribute(null, "class");

我选择用后面一种,这样会把所有class属性去掉,如果只去掉某些类的这个多余的属性,用第一种方式即可。

你可能感兴趣的:(xstream)