首页 > 解决方案 > 如何使用 Java 和 Spring Boot 使用 XML 数据

问题描述

我需要使用 XML 数据。 我的 XML 片段:

<TallyTransferResponse>
    <Response>
        <TransactionDocumentNo>iut-1</TransactionDocumentNo>
        <FromLocation>Bangalore</FromLocation>
        <ToLocation>Noida</ToLocation>
    </Response>
    <Response>
        <TransactionDocumentNo>iut-2</TransactionDocumentNo>
        <FromLocation>Bangalore</FromLocation>
        <ToLocation>Mumbai</ToLocation>
    </Response>
</TallyTransferResponse>

这是实体类的代码:

@Entity
public class TallyTransferResponse{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String transaction_document_no;
    private String from_location;
    private String to_location;
public TallyTransferResponse() {}
    /**
     * @param transaction_document_no
     * @param from_location
     * @param to_location
     */
    public TallyTransferResponse(String transaction_document_no, String from_location, String to_location) {
        this.transaction_document_no = transaction_document_no;
        this.from_location = from_location;
        this.to_location = to_location;
    }
//Getters and Setters
}

我不知道如何编写服务和控制器来使用这个 XML。

标签: javaxmlspring-bootjackson

解决方案


您可以使用 spring 的 restTemplate 向端点发出(get/post)请求,并将响应作为字符串获取,例如:

final ResponseEntity<String> response = restTemplate.getForEntity(endpointUrl, String.class);

并将其映射到 XML 或 JOSN。更直接的版本可能是在响应中请求并期望数据模型,例如:

final ResponseEntity<Company> response = restTemplate.getForEntity(endpointUrl, Company.class);

在这种情况下,您必须向模型类添加一些 XML 绑定注释,例如:

@XmlRootElement(name="company", namespace="some.namespace" )
@XmlAccessorType(XmlAccessType.NONE)
public class Company {
@XmlAttribute(name="id")
private Integer id;
@XmlElement(name="company_name")
private String companyName;
.....
//the rest of the class is omitted

您可以通过向请求添加一个额外的标头来从服务端点请求 JSON 响应,例如:

Accept: application/json

那么数据模型类就不能省略所有的 XML 绑定注解。


推荐阅读