Search code examples
javaxmlxstream

Xstream - Remove value tag


I've got the following xsd tag:

<xs:complexType name="documentation">
<xs:simpleContent>
  <xs:extension base="xs:string">
    <xs:attribute type="xs:string" name="language" use="required"/>
  </xs:extension>
</xs:simpleContent>

this generates (with jax-b):

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "documentation", propOrder = {
"value"
})
public class Documentation {

  @XmlValue
  protected String value;
  @XmlAttribute(name = "language", required = true)
  protected String language;

And I want some output like:

<documentation language="NL">SomeValue</documentation>

but Xstream generates:

<documentation language="NL">
  <value>SomeValue</value>
</documentation>

how could I remove the value tags? I don't want them..

Code to generate the xml tags (this is just a snippet..):

private void createDocumentation(Description description, String docNL) {
    List<Documentation> documentations = description.getDocumentation();
    Documentation documentationNL = new Documentation();
    documentationNL.setLanguage("NL");
    documentationNL.setValue(docNL);
    documentations.add(documentationNL);
}

private void createXmlFile(Description description) {

    XStream xstream = new XStream(new DomDriver());
    xstream.alias("description", Description.class);
    xstream.alias("documentation", Documentation.class);

    xstream.addImplicitCollection(Description.class, "documentation");  
    xstream.useAttributeFor(Documentation.class, "language");

    String xml = xstream.toXML(description);
}

Solution

  • One option is to create a custom converter for your Documentation object.

    Take a look at the XStream Converter tutorial

    EDIT TS:

    adding:

            xstream.registerConverter(new DocumentationConverter());
    

    and

    public class DocumentationConverter implements Converter {
    
    public boolean canConvert(Class clazz) {
        return clazz.equals(Documentation.class);
    }
    
    public void marshal(Object value, HierarchicalStreamWriter writer,
            MarshallingContext context) {
        Documentation documentation = (Documentation) value;
        writer.addAttribute("language", documentation.getLanguage());
        writer.setValue(documentation.getValue());
    }
    
    public Object unmarshal(HierarchicalStreamReader reader,
            UnmarshallingContext context) {
        Documentation documentation = new Documentation();
        reader.moveDown();
        documentation.setLanguage(reader.getAttribute("language"));
        documentation.setValue(reader.getValue());
        reader.moveUp();
        return documentation;
    }
    
    }
    

    did the job