【问题标题】:Need XML root element without end tag using JAXB STAX in combination需要结合使用 JAXB STAX 的没有结束标记的 XML 根元素
【发布时间】:2020-08-21 06:43:02
【问题描述】:

我正在尝试将列表编组为 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;
}

问题是 nillable 不能应用于 XmlRootElement

【问题讨论】:

    标签: java jaxb stax


    【解决方案1】:

    虽然预期和实际在技术上是相等的,但我发现没有办法在不创建额外包装类的情况下修改它。

    【讨论】:

      猜你喜欢
      • 2015-07-05
      • 1970-01-01
      • 2018-04-20
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2012-08-20
      • 1970-01-01
      相关资源
      最近更新 更多