2016-09-23 193 views
1

有一個調用應用程序的Web服務的代碼。如何解析URI中的XML響應

- uri: 
     url: http://10.164.52.61:8080/ems/v74/ws/customer.ws?customerRefId=f4XXXb15d69c3 
     method: GET 
     content_as_json: true 
     password: admin 
     user: admin 
     validate_certs: no 
     return_content: yes 
     HEADER_Cookie: "{{login.set_cookie}}" 
     register: customerId 

     - debug: 
      var: customerId.content 

樣本響應是

"customerId.content": "<listResponse type=\"customer\" count=\"1\"><instance customerId=\"28\" name=\"abc\" customerRefId=\"xyz\" refId1=\"12\" type=\"org\" enabled=\"true\" phone=\"\" fax=\"\" billingZip=\"\" billingAddress=\"\" billingCity=\"\" billingCountry=\"\" billingState=\"\" vendor=\"1\" defaultEmail=\"test\" defaultContactName=\"test\"/></listResponse>" 

我要訪問我的代碼下一個塊列表響應。就像我只需要「customerId」的值。如何使用非對稱性來實現這一點

回答

2

開箱即用的Ansible沒有XML支持。
您可以使用正則表達式過濾器在您的XML數據中進行一些簡單的搜索。
在您的例子:

- debug: msg="{{ customerId.content | regex_findall('customerId=\"(\d+)\"') }}" 

將搜索customerId=\"<number>\"字符串和引號返回號碼列表。

更新:完全工作的例子:

- hosts: localhost 
    gather_facts: no 
    vars: 
    myvar: "<listResponse type=\"customer\" count=\"1\"><instance customerId=\"28\" name=\"abc\" customerRefId=\"xyz\" refId1=\"12\" type=\"org\" enabled=\"true\" phone=\"\" fax=\"\" billingZip=\"\" billingAddress=\"\" billingCity=\"\" billingCountry=\"\" billingState=\"\" vendor=\"1\" defaultEmail=\"test\" defaultContactName=\"test\"/></listResponse>" 
    tasks: 
    - debug: msg="{{ myvar | regex_findall('customerId=\"(\d+)\"') }}" 

我用ansible 2.1.1.0

+0

我有這個同樣的問題,而不是讓我得到什麼是味精中提到的任何值。就像這種情況一樣,它是「msg」:「{{customerId.content | regex_findall(\」customerId = \\\「(\\ d +)\\\」「)」}}「。這是這個特定任務的結果。 –

+0

這不工作.. –

+0

我已經更新了完整的工作示例的答案,請檢查它。 –

0

它值得看這ansible-xml。它不是Ansible的一部分,但它是一個用於解析xml的超級有用模塊,它使用底層的lxml Python庫。

0

從Ansible 2.4,你可以這樣做:

- get_url: 
    url: http://10.164.52.61:8080/ems/v74/ws/customer.ws?customerRefId=f4XXXb15d69c3 
    dest: ./response.xml 
    url_password: admin 
    url_user: admin 
    validate_certs: no 
    headers: 
     Cookie: "{{login.set_cookie}}" 

- xml: 
    path: ./response.xml 
    xpath: /listResponse/instance 
    content: attribute 
    register: instance_attributes 

- debug: 
    var: instance_attributes.matches.0.instance.customerId