java—需要不带结束标记的xml根元素,并结合使用jaxb stax

ut6juiuv  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(376)

我正在尝试将列表封送到xml。由于xml包含列表,我不想为outer标记创建单独的类,所以我将结合使用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;
}

问题为nillable不能应用于xmlrootelement

eagi6jfj

eagi6jfj1#

虽然预期的和实际的在技术上是相等的,但是我发现如果不创建额外的 Package 器类,就没有办法修改它。

相关问题