结合使用JAXB STAX需要不带结束标签的XML根元素

问题描述

我正在尝试将列表编组为xml。由于xml包含列表,并且我不想为外部标记创建单独的类,因此我将STAX和JAXB结合使用。

问题是我正在获取带有结束标记的元素。 实际产量

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

预期产量

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

文件

@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;
    }
}

方法

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;
}

问题是不可适用的,不能应用于XmlRootElement

解决方法

尽管期望值和实际值在技术上都是相等的,但我发现无法在不创建其他包装器类的情况下进行修改。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...