Python Ansible:读取属性值并访问它的XML模块
我正在使用Ansible playbook从XML文件中提取特定属性值,如中所述,但出现错误“Xpath/business/website/validxhtml不引用节点” XML文件:Python Ansible:读取属性值并访问它的XML模块,python,xml,linux,ansible,Python,Xml,Linux,Ansible,我正在使用Ansible playbook从XML文件中提取特定属性值,如中所述,但出现错误“Xpath/business/website/validxhtml不引用节点” XML文件: <business type="bar"> <name>Tasty Beverage Co.</name> <beers> <beer>Rochefort 10</beer> <beer>St
<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>
答复:
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页面中指定的示例相同,但不确定它失败的原因。请帮助。这是因为示例xml中既不存在
validxhtml
元素,也不存在属性。首先,像HTML一样的XML有元素和属性,两者都是不同的东西
因此,您需要添加validxhtml
元素以及要提取的属性和值,或者在xml文件中使用其他具有属性的元素,例如10
。我希望这有帮助
[更新]
根据请求,如果只想获取元素值,请尝试此操作,它应返回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
您的XPath是/business/website/validxhtml
,您的XML文件不包含
元素,您会收到错误“XPath未引用节点”。。。这是一个非常简单的错误。您好,请帮助我了解更多信息,我已尝试更改xpath:/business/rating&var:xmlresp.matches[0]。rating.validatedon。。(例如,从评级中提取值“10”),但我得到的是未定义变量的Ok响应。我的目的是从XML文件中提取特定属性,从评级中提取值“10”,或者可能是website/address下的字符串“”。value10
&tastybeverageco.com
是元素值。因此,要获得元素值,只需指定xpath中的content:text
。非常感谢……当我使用xmlresp.matches时,得到了所需的值,即值“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