我需要将 JavaBeans 编组到 org.w3c.dom.Element
我可以编组到输出流,但不能编组到 XML 文档。
我写了以下测试代码:
JAXBContext context = JAXBContext.newInstance(String.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
String xmlRootName = "rootTag";
JAXBElement jaxbElement = new JAXBElement(new QName("", xmlRootName), String.class, "foo bar");
Element element;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
m.marshal(jaxbElement, doc);
System.out.println("Document: " + doc);
element = doc.createElement(xmlRootName);
m.marshal(jaxbElement, element);
System.out.println("Element1: " + element);
DOMResult res = new DOMResult();
m.marshal(jaxbElement, res);
element = ((Document)res.getNode()).getDocumentElement();
System.out.println("Element2: " + element);
StringWriter writer = new StringWriter();
m.marshal(jaxbElement, writer);
System.out.println("Writer: " + writer);
输出是:
Document: [#document: null]
Element1: [rootTag: null]
Element2: [rootTag: null]
Writer: <rootTag>foo bar</rootTag>
看起来编组仅适用于输出流。如何编组到 xml 文档?
我究竟做错了什么?