我有以下 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
从 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);
我是一名优秀的程序员,十分优秀!