【问题标题】:Add DOM nodes as Any objects to JAXB class将 DOM 节点作为 Any 对象添加到 JAXB 类
【发布时间】:2017-03-22 01:02:58
【问题描述】:

我有一个包含任何元素的 jaxb 类:

@XmlAnyElement(lax = true)
protected List<Object> any;

我想以编程方式向其中添加 DOM 节点,然后将其编组为 XML。基本上,我尝试的是创建一个节点,然后将其添加到任何列表中:

QName qn = new QName(...);
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
doc = f.newDocumentBuilder().newDocument();
Node node = doc.createElementNS(qn.getNamespaceURI(), qn.getLocalPart());
myJaxbClass.getAny().add(node); 

然后我进行编组:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
// Marshal the Object to a Document
JAXBContext jc2 = JAXBContext.newInstance(BookEntry.class);
Marshaller marshaller = jc2.createMarshaller();
marshaller.marshal(book, document);

将整个 Jaxb 类编组回 xml 失败并出现异常:

com.sun.istack.SAXException2:无法将类型“MyApp.MyJaxBClass.BookEntry”编组为元素,因为它缺少@XmlRootElement 注释]

如何以编程方式正确地将节点添加到任何列表?

【问题讨论】:

    标签: java xml jaxb


    【解决方案1】:

    您必须提供一个根 XML 元素,这对于每个有效的 XML 文档基本上都是必需的。 我自带了两种声明根元素的方法。

    A) 在代码中,创建一个根 JAXBElement 并将其传递给 marshaller:

    QName qName = new QName("com.example.jaxb.model", "book-entry");
    JAXBElement<BookEntry> root = new JAXBElement<BookEntry>(qName, BookEntry.class, book);
    ...
    marshaller.marshal(root, document);
    

    B) 使用 @XmlRootElement(...) 注释您的模型:

    @XmlRootElement(name = "book-entry", namespace = "com.example.jaxb.model")
    public class BookEntry { ... }
    

    两种选择都应该产生相同的结果。

    【讨论】:

    • 谢谢!将我的 Jaxb 类包装在 JAXBElement 中就可以了。所以 A) 为我工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 2023-03-30
    • 2021-01-10
    • 2018-07-13
    • 1970-01-01
    • 2017-04-28
    相关资源
    最近更新 更多