You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring RestTemplate如何解析text/xml响应中的整数内容

解决方案

方法一:手动解析XML字符串

先以String类型获取完整响应,再通过XML解析工具或正则提取数字:

使用JDK原生XML解析(推荐,更严谨)

// 获取XML响应字符串
String xmlResponse = REST_TEMPLATE.exchange(
    new URI(PropertyConfig.endPointUrl), 
    HttpMethod.POST, 
    httpEntity, 
    String.class
).getBody();

// 初始化解析工具
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // 开启命名空间支持
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlResponse)));

// 使用XPath定位<int>节点
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
    @Override
    public String getNamespaceURI(String prefix) {
        return "ns".equals(prefix) ? "http://tempuri.org/" : XMLConstants.NULL_NS_URI;
    }

    @Override
    public String getPrefix(String namespaceURI) { return null; }
    @Override
    public Iterator<String> getPrefixes(String namespaceURI) { return null; }
});

// 提取数字并转换为Integer
String numberStr = xpath.evaluate("//ns:int", doc);
Integer result = Integer.parseInt(numberStr);

使用正则表达式(仅适合结构固定的简单XML)

String xmlResponse = REST_TEMPLATE.exchange(
    new URI(PropertyConfig.endPointUrl), 
    HttpMethod.POST, 
    httpEntity, 
    String.class
).getBody();

Pattern pattern = Pattern.compile("<int.*?>(\\d+)</int>");
Matcher matcher = pattern.matcher(xmlResponse);
if (matcher.find()) {
    Integer result = Integer.parseInt(matcher.group(1));
    // 处理结果
}

方法二:定义实体类映射XML

创建对应XML结构的实体类,利用JAXB注解实现自动转换:

1. 定义实体类

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "int", namespace = "http://tempuri.org/")
public class IntResponse {
    private int value;

    // 必须提供无参构造方法
    public IntResponse() {}

    public IntResponse(int value) {
        this.value = value;
    }

    // JAXB需要Getter/Setter
    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}

2. 调用接口并转换

IntResponse response = REST_TEMPLATE.exchange(
    new URI(PropertyConfig.endPointUrl), 
    HttpMethod.POST, 
    httpEntity, 
    IntResponse.class
).getBody();
Integer result = response.getValue();

注意:Java 9及以上版本默认移除了JAXB模块,若使用Spring Boot需添加相关依赖:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <scope>runtime</scope>
</dependency>

方法三:自定义HttpMessageConverter(全局复用场景)

如果需要频繁处理这类简单XML响应,可以自定义HttpMessageConverter,直接将<int>节点转换为Integer类型,配置到RestTemplate后即可直接用Integer.class接收响应。


内容的提问来源于stack exchange,提问作者Thilina Sandaruwan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 18:31:02