【问题标题】:How can I convert object (JAXB) or byte[] (from this object) to `org.w3c.dom.Element`?如何将对象 (JAXB) 或 byte[] (来自此对象) 转换为 `org.w3c.dom.Element`?
【发布时间】:2018-08-28 11:43:04
【问题描述】:

例如,我有 Java 类 (JAXB):

Test test = new Test();
test.set....
//fill test object
............

现在我需要将此对象转换为org.w3c.dom.Element

现在我有转换为byte[]的转换器:

public <T> byte[] marshal(T value) {
    try {
      StringWriter sw = new StringWriter();
      Marshaller marshaller = jaxbContext.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      marshaller.marshal(value,sw);
      return sw.toString().getBytes();
    } catch (JAXBException e) {
      throw new RuntimeException(e.getMessage());
    }
  }

我的问题是:如何将testbyte[] 转换为to org.w3c.dom.Element

编辑:

回答评论中的问题我为什么需要它

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.w3c.dom.Element;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "any"
})
@XmlRootElement(name = "MessagePrimaryContent")
public class MessagePrimaryContent {

    @XmlAnyElement
    protected Element any;


    public Element getAny() {
        return any;
    }


    public void setAny(Element value) {
        this.any = value;
    }

}

我需要将我的对象设置为setAny 方法。这样的协议和格式。不是我发明的

【问题讨论】:

  • 你为什么要这样做?通常,您使用 jaxb 或 dom 模型。
  • @daniu 我回答了问题
  • DocumentBuilderFactory.newInstance().newDocumentBuilder()创建新元素?
  • @ulab 问题是关于如何将对象编组为 DOM 元素。不是关于如何简单地创建一个新的 DOM 元素。

标签: java jaxb marshalling


【解决方案1】:

首先,我会使用@XmlAnyElement(lax = true) Object any 而不是@XmlAnyElement Element any。然后您可以简单地将您的 test 分配给 any 并让 JAXB 编组它。看到这个答案:

https://stackoverflow.com/a/9692275/303810

因此您可以避免预先编组为 DOM。


现在,回答你的问题。

您基本上想将您的 test 对象编组为 DOM 元素。最简单的方法是编组到 DOMResult,然后从那里获取元素。

类似:

  marshaller = jaxbContext.createMarshaller();
  DOMResult domResult = new DOMResult();
  marshaller.marshal(value, domResult);
  Node rootNode = domResult.getNode();
  // I'm not quite sure that it's always a Document, but it's easy to figure out
  final Element rootElement = ((Document) rootNode).getDocumentElement();

【讨论】:

    猜你喜欢
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多