OK OK 2...">

Map attributes in xstream

I have XML like this:

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

      

Class:

public class Qualification {
  @XStreamAsAttribute
  private String name;

  private String requesturi;
}

      

How can I match <attribute name="abc">OK</attribute>

+3


source to share


1 answer


After writing the attribute converter. The problem has been resolved.

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

class:

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());

  } 

}

      



Use this in class Qualifications like:

  @XStreamConverter(AttributeConverter.class)
  private Attribute attribute;

      

Case converter in main class:

xstream.registerConverter(new AttributeConverter());

      

+1


source







All Articles