Java dom:将节点转换为根元素



我有以下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>

为了使文件我需要仅保留标签<AffaireByTiersResponse>作为根元素,然后将其名称更改为 <Affaires>

最好的方法是什么?

可以使用 javax.xml.soap.MessageFactory来完成从肥皂信封中提取基础内容。

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();

然后可以重命名root节点

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

然后可以将此文档传递到jaxb umarshaller

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

最新更新