python - Ansible:读取属性值并访问它的 XML 模块

标签 python xml linux ansible

我正在使用 Ansible playbook 从 XML 文件中提取特定的属性值,如 the Ansible XML module page 中所述。 ,但收到错误“Xpath/business/website/validxhtml 未引用节点”。

XML 文件:

<business type="bar">
  <name>Tasty Beverage Co.</name>
    <beers>
      <beer>Rochefort 10</beer>
      <beer>St. Bernardus Abbot 12</beer>
      <beer>Schlitz</beer>
    </beers>
  <rating subjective="true">10</rating>
  <website>
    <mobilefriendly/>
    <address>http://tastybeverageco.com</address>
  </website>
</business>

YAML 文件:

- name: Read an element's attribute values
  xml:
    path: /home/ansible/test.xml
    xpath: /business/website/validxhtml
    content: attribute
  register: xmlresp

- name: Show an attribute value
  debug:
    var: xmlresp.matches[0].validxhtml.validatedon

回应:

PLAY [testing XMl values] ************************************************************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************************************************
ok: [localhost]

TASK [Read an element's attribute values] ********************************************************************************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "msg": "Xpath /business/website/validxhtml does not reference a node!"}

PLAY RECAP ***************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

我使用的示例与 Ansible xml 页面中指定的相同,但不确定为什么失败。请帮忙。

最佳答案

因为 validxhtml 都不是元素不存在 attribute在示例 xml 中。首先,像 HTML 一样,XML 也有元素和属性,两者是不同的东西 Ref

因此您需要添加 validxhtml您想要提取具有属性和值的元素或使用具有属性的其他元素,例如 <rating subjective="true">10</rating>在 xml 文件中。我希望这会有所帮助。

[更新] 根据要求,如果您只想获取元素值,只需尝试此操作,它应该返回 10 .

- name: Read an element's attribute values
  xml:
    path: /home/ansible/test.xml
    xpath: /business/rating
    content: text
  register: xmlresp

- name: Show an attribute value
  debug:
    var: xmlresp.matches

关于python - Ansible:读取属性值并访问它的 XML 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57738373/

相关文章:

Python:如何在跳过最后一个值后获取 Pandas 数据框中的前 5 个值?

python - 如何从命令行界面访问 Canopy 终端?

python - Pandas 在正则表达式上 split

c++ - 使用 XSD 的单元测试 xml 生成器

c++ - PugiXML 没有错误的空文档

linux - Linux 上 .com.zerog.registry.xml 文件的自定义 InstallAnywhere 位置

c - 将文本追加到现有的 UTF16LE 文件

python - 获取用户在 Flask 中的位置

python - 领域特定语言,标准文件格式

linux - 如何通过导入将图像发送到程序而不是保存它?