在xstream中映射属性

时间:2013-02-15 12:03:01

标签: java xml xstream

我有这样的XML:

<qualification name="access">
    <attribute name="abc">OK</attribute>
    <attribute name="res">OK 2</attribute>
    <requesturi>http://stackoverflow.com</requesturi>
</qualification>

班级是:

public class Qualification {
  @XStreamAsAttribute
  private String name;

  private String requesturi;
}

如何映射<attribute name="abc">OK</attribute>

1 个答案:

答案 0 :(得分:1)

编写属性转换器后。问题解决了。

package com.xstream;

import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

public class Attribute {

  @XStreamAsAttribute
  private String name;

  private String value;

  public Attribute(String name, String value) {
    this.name = name;
    this.value = value;
  }

  /**
   * @return the name
   */
  public String getName() {
    return name;
  }

  /**
   * @param name the name to set
   */
  public void setName(String name) {
    this.name = name;
  }

  /**
   * @return the value
   */
  public String getValue() {
    return value;
  }

  /**
   * @param value the value to set
   */
  public void setValue(String value) {
    this.value = value;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return "Attribute [name=" + name + ", value=" + value + "]";
  }

}

AttributeConverter课程是:

package com.xstream;

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;

public class AttributeConverter implements Converter{

  @Override
  public boolean canConvert(Class clazz) {
    return clazz.equals(Attribute.class);
  }

  @Override
  public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext context) {
    System.out.println("object = " + object.toString());
    Attribute attribute = (Attribute) object;
    writer.addAttribute("name", attribute.getName());  
    writer.setValue(attribute.getValue());  

  }

  @Override
  public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    return new Attribute(reader.getAttribute("name"), reader.getValue());

  } 

}

在Qualification类中使用此项:

  @XStreamConverter(AttributeConverter.class)
  private Attribute attribute;

在主类中注册转换器:

xstream.registerConverter(new AttributeConverter());