gpt4 book ai didi

Java DOM : transforming a node to a root element

转载 作者:太空宇宙 更新时间:2023-11-04 11:41:09 24 4
gpt4 key购买 nike

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

关于Java DOM : transforming a node to a root element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42766535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com