首页 > 解决方案 > Xpath 使用 Spring DSL 查找 XML 的根

问题描述

我正在使用 Spring DSL 来访问网络服务器,就像这样,

<route>
    <!-- 1 -->
    <from uri="...">
    <!-- 2 -->
    <to uri="...">
    <!-- 3 -->
    <choice>
        <when>
            <xpath></xpath>
            <to uri="...">
        </when>
        <when>
            <xpath></xpath>
            <to uri="...">
        </when>
    </choice>
</route>

<!-- 1 -->当端点命中时, <!-- 2 -->向 Web 服务器发送请求,<!-- 3 -->检查作为响应从 Web 服务器接收的根元素,基于该响应 XML 将发送到另一个端点

Webserver 将返回 2 个 XML 消息中的任何一个,例如,

<tns:roottag xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance xmlns:tns="http://example.com">
    <tns:leaftag>
        information
    </tns:leaftag>
</tns:roottag>

或者

<tns:Parenttag xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance xmlns:tns="http://example.com">
    <tns:Childtag>
        information
    </tns:Childtag>
</tns:parenttag>

从 Web 服务器接收到 XML 后,需要检查根目录是否会对接收到的 XML 执行不同的操作,

参考了一些网站后,我才知道XPath在spring DSL可以用于条件,

我的问题: 1. 仅从响应 XML 中检索根标记名称(如下所示)并根据 XPath 检查对原始响应 XML 执行不同的操作

tns:Parenttag xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance xmlns:tns="http://example.com" ==> Parenttag

或者

tns:roottag xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance xmlns:tns="http://example.com" ==> roottag

标签: xmlxpathspring-dsl

解决方案


这只会在顶级元素是 a 时匹配<tns:roottag>

<xpath>/tns:roottag</xpath>

并且这只会在顶级元素是 a 时匹配<tns:Parenttag>

<xpath>/tns:Parenttag</xpath>

但是,在这可以工作之前,您需要声明tns前缀。您可以在<beans>顶部元素上执行此操作:

<beans
    xmlns="http://www.springframework.org/schema/beans"
    ...other namespace declarations...
    xmlns:tns="http://example.com"
>

确保命名空间 URI 与 XML 响应中的匹配。


推荐阅读