Search code examples
javajaxbstax

Need XML root element without end tag using JAXB STAX in combination


I am trying to marshal list to xml. As the xml contains list and I do not want to create separate class for outer tag I am using STAX and JAXB in combination.

The issue is I am getting element with end tag. actual output

<WRAPPER>
    <ROOT att1="val1" att2="val2"></ROOT>
    <ROOT att1="val1" att2="val2"></ROOT>
</WRAPPER>

Expected Output

<WRAPPER>
    <ROOT att1="val1" att2="val2"/>
    <ROOT att1="val1" att2="val2"/>
</WRAPPER>

Class file

@XmlRootElement(name="ROOT")
@XmlAccessorType(XmlAccessType.FIELD)
public class ROOT {

    @XmlAttribute(name = "att1")
    String att1;
    
    @XmlAttribute(name = "att2")
    String att2;

    public String getAtt1() {
        return att1;
    }

    public void setAtt1(String att1) {
        this.att1 = att1;
    }

    public String getAtt2() {
        return att2;
    }

    public void setAtt2(String att2) {
        this.att2 = att2;
    }
}

Method

public static String marshal(List<ROOT> list)
    throws XMLStreamException, JAXBException, IOException {
    JAXBElement<ROOT> jaxb = null;
    String xmlString = null;
    if (!CollectionUtils.isEmpty(list)) {
        QName root = new QName("ROOT");
        XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
        StringWriter stringWriter = new StringWriter();
        
        XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(stringWriter);
        streamWriter.writeStartElement("WRAPPER");
        JAXBContext jc = JAXBContext.newInstance(ROOT.class);
        Marshaller marshaller = jc.createMarshaller();
        for (ROOT t : list) {
            jaxb = new JAXBElement<ROOT>(root, ROOT.class, t);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            marshaller.marshal(jaxb, streamWriter);
        }
        streamWriter.writeEndDocument();
        xmlString = stringWriter.toString();
        stringWriter.close();
        streamWriter.close();
        }
    return xmlString;
}

Problem is nillable cannot be applied to XmlRootElement


Solution

  • Although both expected and actual are technically equal I found no way to modify that in the way without creating additional wrapper class.