如何编组JAXB对象到org.w3c.dom.Document? [英] how to marshal a JAXB object to org.w3c.dom.Document?

查看:144
本文介绍了如何编组JAXB对象到org.w3c.dom.Document?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这给我一个没有子节点的顶级节点的Document对象:

This gives me a Document object with a top level node with no child nodes:

public static Document getDocument(Object jaxb)
{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    //dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument(); 

    JAXBContext context = JAXBContext.newInstance(jaxb.getClass());
    context.createMarshaller().marshal(jaxb, doc);

    return doc;
}

这是解决方法,这似乎更为低效,因为它转换为String然后到Document。

This is the workaround, which seems even more inefficient, since it converts to String and then to Document.

public static Document getDocument(Object jaxb)
{                           
    StringWriter writer = new StringWriter();       
    JAXBContext context = JAXBContext.newInstance(jaxb.getClass());
    context.createMarshaller().marshal(jaxb, writer);

    return DocumentBuilderFactory.newInstance().newDocumentBuilder().
parse(new InputSource(new StringReader(writer.toString()));
}

可以完成我想要完成的工作吗?

Is it possible to accomplish what I'm trying to accomplish?

推荐答案

是一个例子:

域模型(Foo)

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Foo {

    private String bar;

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

}

演示 / p>

Demo

import javax.xml.bind.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Create the JAXBContext
        JAXBContext jc = JAXBContext.newInstance(Foo.class);

        // Create the Object
        Foo foo = new Foo();
        foo.setBar("Hello World");

        // Create the Document
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();

        // Marshal the Object to a Document
        Marshaller marshaller = jc.createMarshaller();
        marshaller.marshal(foo, document);

        // Output the Document
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(System.out);
        t.transform(source, result);
    }

}

输出

<?xml version="1.0" encoding="UTF-8" standalone="no"?><foo><bar>Hello World</bar></foo>

这篇关于如何编组JAXB对象到org.w3c.dom.Document?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆