【问题标题】:Java DOM: transforming a node to a root elementJava DOM:将节点转换为根元素
【发布时间】:2017-03-13 14:47:44
【问题描述】:

我尝试将以下 XML 文件(SOAP 响应)映射到 Java 对象:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <ns2:AffaireByTiersResponse xmlns:ns2="http://service.hibernate.com/">
      <Affaire>
        <code_produit>Cred</code_produit>
        <id>1</id>
        <montant_fin>2000.0</montant_fin>
        <id_tier>1</id_tier>
      </Affaire>
      <Affaire>
        <code_produit>Cred</code_produit>
        <id>2</id>
        <montant_fin>25000.0</montant_fin>
        <id_tier>1</id_tier>
      </Affaire>
    </ns2:AffaireByTiersResponse>
  </soap:Body>
</soap:Envelope>

为了编组文件,我只需要保留标签&lt;AffaireByTiersResponse&gt; 作为根元素并将其名称更改为&lt;Affaires&gt;

最好的方法是什么?

【问题讨论】:

  • “映射到 Java 对象”...您是指 JAXB 还是类似的?
  • 是的,我打算使用 JAXB Unmarshaller(我已经测试过了)
  • AFAIK,您可以使用Document#renameNode 重命名节点。然后 Unmarshaller 可以解组该元素。虽然不确定细节。所以你必须自己弄清楚。

标签: java xml dom


【解决方案1】:

可以使用javax.xml.soap.MessageFactory 从 SOAP 信封中提取底层内容。

String example = new String(Files.readAllBytes(Paths.get("input.xml")), StandardCharsets.UTF_8);
SOAPMessage message = MessageFactory.newInstance().createMessage(null,
        new ByteArrayInputStream(example.getBytes()));

Document doc = message.getSOAPBody().extractContentAsDocument();

Element root = doc.getDocumentElement();

然后可以重命名根节点

doc.renameNode(root, root.getNamespaceURI(), "Affaires");

然后可以将此文档传递到 JAXB 解组器

Unmarshaller unmarshaller = JAXBContext.newInstance(Affaires.class).createUnmarshaller();
Affaires farm = (Affaires) unmarshaller.unmarshal(doc);

【讨论】:

  • 非常感谢,愚蠢的我不知道 Document doc = message.getSOAPBody().extractContentAsDocument(); 和 renameNode() 函数。
  • 我知道这个答案已经很老了,但是在发回响应之前更改根元素与生成的 WSDL 没有区别吗?
猜你喜欢
  • 2018-10-25
  • 2011-11-19
  • 2010-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2012-12-02
相关资源
最近更新 更多