我正在使用 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/