如何使用 JAXB 在 Java 中将 JAXBElement<Object> 编组到 org.w3c.dom.Element

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13569572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:15:11  来源:igfitidea点击:

How to marshall JAXBElement<Object> into org.w3c.dom.Element in Java using JAXB

javajaxbelement

提问by Constantine Gladky

I need to get Element object with request. I have ObjectFactory. I created an JAXBElement, and I need to marshall it to Element. Could anyone help me?

我需要通过请求获取 Element 对象。我有对象工厂。我创建了一个 JAXBElement,我需要将它编组到 Element。有人可以帮助我吗?

回答by Ian Roberts

You could marshal to a DOMResult:

你可以编组到一个DOMResult

DOMResult res = new DOMResult();
marshaller.marshal(myJaxbElement, res);
Element elt = ((Document)res.getNode()).getDocumentElement();

回答by poseidon

In addition to Ian's answer, I suppose to first create a Document, as the unchecked cast can be omitted this way:

除了伊恩的回答,我想首先创建一个文档,因为可以通过这种方式省略未经检查的强制转换:

Document document =
    DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
JAXB.marshal(jaxbElement, new DOMResult(document));
Element element = document.getDocumentElement();