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

Ansible无法通过XPath读取XML属性的问题求助

解决Ansible读取XML命名空间下元素属性的问题

问题分析

你的XML根元素composite属于默认命名空间http://xmlns.oracle.com/sca/1.0,属性revision没有命名空间前缀(XML属性不会默认继承元素的命名空间)。你当前的XPath写法/sca:composite/@revision语法本身正确,但Ansible的xml模块在直接定位属性节点时,可能因命名空间处理的特殊逻辑导致报错。

解决方案

方案1:通过元素节点提取属性(推荐)

先定位到composite元素节点,将content设为dictionary,再从返回的字典结构中提取属性值:

- name: 'Get composite element'
  xml:
    path: 'composite.xml'
    xpath: '/sca:composite'
    content: dictionary
    namespaces:
      sca: 'http://xmlns.oracle.com/sca/1.0'
  register: composite_data

- name: 'Extract revision value'
  debug:
    msg: "Revision is: {{ composite_data.matches[0].composite.revision }}"

方案2:使用无命名空间前缀的XPath定位

如果不想依赖命名空间配置,可以用local-name()忽略命名空间直接匹配元素:

- name: 'Get revision'
  xml:
    path: 'composite.xml'
    xpath: '/*[local-name()="composite"]/@revision'
    content: attribute
  register: my_revision

- debug:
    msg: "Revision is: {{ my_revision.matches[0].revision }}"

错误写法说明

你尝试的/sca:composite/@sca:revision是错误的——你的revision属性并没有sca前缀,不属于该命名空间,因此无法匹配到目标节点。

内容的提问来源于stack exchange,提问作者Michael C

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 18:42:38