Suppose you have XML like this
- <code><qualification name="access">
- <attribute name="abc">OK</attribute>
- <requesturi>http://stackoverflow.com</requesturi>
- </qualification>
Class is:
- public class Qualification {
- @XStreamAsAttribute
- private String name;
- private String requesturi;
- }
Now we’ll map this line attributes here:
—————–
We have to write converter.
- 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 is:
- 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 Qualification class as:
- @XStreamConverter(AttributeConverter.class)
- private Attribute attribute;
Register converter in main class as:
- xstream.registerConverter(new AttributeConverter());