问题
I have a below mentioned xml:
<?xml version='1.0' encoding='UTF-8'?>`
<Envelope>
<Body>
<response>
<timestamp>2018-11-01T15:18:44-04:00</timestamp>
<content>`
<element1>value1</element1>
<element2>value2(/element2>
<element3>
<child1>c1</child1>
<child2>c2</child2>
</element3>
</content>
</response>
</Body>
</Envelope>
I have to capture the content tag children in xml format only to encode it.
when I use xml module to get the content and its descendants, captured as list of dictionaries.
All I want is I should capture the content as a string like
"<element1>value1</element1>
<element2>value2(/element2>
<element3>
<child1>c1</child1>
<child2>c2</child2>
</element3>"
as a string.
Later I will use this string to encode and decode.
I do not want to encode each and every descendant of content, but all the content together.
How can I achieve this using ansible. I am using ansible version 2.4
回答1:
Based off reading the Ansible xml module, it doesn't seem possible.
You can use the command module using a utility like xmllint to do it like this:
---
- name: run the playbook tasks on the localhost
hosts: 127.0.0.1
connection: local
tasks:
- name: Get Content Section
command: "xmllint --xpath '/Envelope/Body/response/content' --format test.xml"
register: out
- name: output
debug:
msg: "{{ out.stdout }}"
Which would look like so:
PLAY [run the playbook tasks on the localhost] ***************************************************************************************************
TASK [Gathering Facts] ***************************************************************************************************************************
ok: [127.0.0.1]
TASK [Get Content Section] ***********************************************************************************************************************
changed: [127.0.0.1]
TASK [output] ************************************************************************************************************************************
ok: [127.0.0.1] => {
"msg": "<content><element1>value1</element1><element2>value2</element2><element3><child1>c1</child1><child2>c2</child2></element3></content>"
}
PLAY RECAP ***************************************************************************************************************************************
127.0.0.1 : ok=3 changed=1 unreachable=0 failed=0
回答2:
You can take advantage of the fact that to even use xml: the target python must be available (and have the lxml egg/wheel installed, but we won't need it for this purpose):
vars:
name_of_the_xml_file: whatever-filename
tasks:
- command: '{{ ansible_python_interpreter }} -u - {{ name_of_the_xml_file }}'
args:
stdin: |
import sys
from xml.etree.ElementTree import parse, tostring
with open(sys.argv[1]) as fh:
doc = parse(fh)
c = doc.find('.//content')
print(tostring(c))
register: the_content
- debug: var=the_content.stdout
来源:https://stackoverflow.com/questions/53234342/ansible-read-part-of-xml-as-string-not-as-dict-list