首页 文章

Jaxb可以在没有根元素的情况下编组子元素吗?

提问于
浏览
9

我不确定jaxb是否可以使用以下问题,但无论如何我都会问 .

在某个项目中,我们使用带有定义模式的jaxb来创建xml文件的下一个结构 .

<aaa>
     <bbb>
        more inner children here
     </bbb>
     <bbb>
        more inner children here
     </bbb>
</aaa>

我们还使用自动类生成jaxb来创建类:aaa和bbb, where aaa was generated as the @XmlRootElement.

我们现在想要在新项目中使用相同的模式,该模式也将与之前的项目兼容 . 我想做的是使用相同的jaxb生成的类,而不对模式进行任何更改,以便只将一个bbb对象编组为xml .

JAXBContext jc = JAXBContext.newInstance("generated");
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(bbb, writer);

所以我们会得到下一个结果:

<bbb>
    <inner child1/>
    <inner child2/>
    ...
 </bbb>

我目前无法这样做,因为marshaller大喊我没有定义@XmlRootElement .

我们实际上试图避免将模式分成2个模式的情况,其中一个是bbb,另一个是aaa导入bbb .

提前致谢!

2 回答

  • 15

    我可能迟到了5年:)但你有没有试过这样的事情:

    StringWriter stringWriter = new StringWriter();
    JAXB.marshal(bbb, stringWriter);
    String bbbString = stringWriter.toString();
    
  • 0

    我可能已经晚了3年,但你有没有试过这样的事情:

    public static String marshal(Bbb bbb) throws JAXBException {
        StringWriter stringWriter = new StringWriter();
    
        JAXBContext jaxbContext = JAXBContext.newInstance(Bbb.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    
        // format the XML output
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    
        QName qName = new QName("com.yourModel.bbb", "bbb");
        JAXBElement<Bbb> root = new JAXBElement<Bbb>(qName, Bbb.class, bbb);
    
        jaxbMarshaller.marshal(root, stringWriter);
    
        String result = stringWriter.toString();
        LOGGER.info(result);
        return result;
    }
    

    这是我在没有rootElement时编组/解组的文章:http://www.source4code.info/2013/07/jaxb-marshal-unmarshal-with-missing.html

    它对我来说非常好 . 我正在为寻找答案的其他失落的灵魂写这个回应 .

    祝一切顺利 : )

相关问题