问题陈述:我们正在使用ansible在Windows主机上运行soap-api并尝试从api响应中获取值,但是,由于无效的xpath异常,我们无法获取值。 此活动的主要目的是了解 errorCode 标签的值。但无法获取该值。
下面是我们正在尝试的示例剧本:
---
- name: execute soap api
ansible.windows.win.uri:
url: " "
method: POST
body: |
< body of the soap>
headers:
Content-Type: "text/xml: charset=utf-8"
status_code: 200
return_content: yes
validate_certs: false
register: api_response
- name: set the content of the file
ansible.windows.win.copy:
content: "{{ api_response.content }}"
dest: C:\Temp\response.xml
- name: get result from xml
community.windows.win.xml:
path: C:\Temp\response.xml
content: "xml"
xpath: "/S:Envelope/S:Body/ns10:xyz/retrun/responseservice:status/responseservice:errorCode"
register: soap_result
- name: display soap result
debug:
var: soap_result
下面是示例soap-api 响应:
"<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S=\" ***\">
<S:Body>
<ns10:xyz xmlns:responseservice=\" ***\">
<return>
<responseservice:status>
<responseservice:errorCode>0</responseservice:errorCode>
</responseservice:status>
</return>
</ns10:xyz>
</S:Body>
</S:Envelope>"
以下是我们收到的消息: msg:“提供的 xpath 与任何节点都不匹配。如果这是意外情况,请检查您的 xpath 对于提供的路径中的 xml 文件是否有效
期望: 我们期望从上面的soap api响应中获取errorCode标签的值,即0。
对于有效的 XML 文件
response.xml
,内容为
<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S=" ***">
<S:Body>
<ns10:xyz xmlns:responseservice=" ***">
<return>
<responseservice:status>
<responseservice:errorCode>0</responseservice:errorCode>
</responseservice:status>
</return>
</ns10:xyz>
</S:Body>
</S:Envelope>
一个最小的示例手册
---
- hosts: localhost
gather_facts: false
vars:
XML: "{{ lookup('file', 'response.xml') }}"
YML: "{{ XML | ansible.utils.from_xml }}"
tasks:
- debug:
msg: "{{ YML['S:Envelope']['S:Body'] | json_query('*.return') }}"
将产生
的列表输出TASK [debug] ***********************
ok: [localhost] =>
msg:
- responseservice:status:
responseservice:errorCode: '0'
类似的任务
- debug:
msg: "{{ YML['S:Envelope']['S:Body'] | json_query('*.return.*') | flatten | first }}"
只是结果
TASK [debug] *********************
ok: [localhost] =>
msg:
responseservice:errorCode: '0'