我在下方有xml字符串,并尝试在每个条目标记的 domain,receive_time,serial和seqno 标记之间打印文本。
xml="""
<response status="success" code="19"><result><msg><line>query job enqueued with jobid 19032</line></msg><job>19032</job></result></response>
19032
<response status="success"><result>
<job>
<tenq>14:10:09</tenq>
<tdeq>14:10:09</tdeq>
<tlast>19:00:00</tlast>
<status>ACT</status>
<id>19032</id>
<cached-logs>64</cached-logs>
</job>
<log>
<logs count="20" progress="29">
<entry logid="2473601">
<domain>1</domain>
<receive_time>2017/11/26 14:10:08</receive_time>
<serial>007901004140</serial>
<seqno>10156449120</seqno>
</entry>
<entry logid="2473601">
<domain>1</domain>
<receive_time>2017/11/26 14:10:08</receive_time>
<serial>007901004140</serial>
<seqno>10156449120</seqno>
</entry>
</logs>
</log>
</result></response>
"""
使用xml.etree.ElementTree。为了获得域标记之间的内容,我尝试了 node.attrib.get('domain')或 node.get('domain')。 。请指教
import xml.etree.ElementTree as ET
tree = ET.fromstring(xml)
for node in tree.iter('entry'):
print node
它也可以是其他python库,不必是xml.etree。我不想盲目地在标签之间打印文本,我需要打印标签名称,然后是文本,即:。
domain: 1
receive_time: 2017/11/26 14:10:08
serial: 007901004140
seqno: 10156449120
etc
答案 0 :(得分:2)
您首先使用domain
方法找到find()
标记。然后,tag
属性和text
属性应该获取您要查找的详细信息 -
import xml.etree.ElementTree as ET
tree = ET.fromstring(xml)
for node in tree.iter('entry'):
print('\n')
for elem in node.iter():
if not elem.tag==node.tag:
print("{}: {}".format(elem.tag, elem.text))
希望这有帮助!
输出 -
domain: 1
receive_time: 2017/11/26 14:10:08
serial: 007901004140
seqno: 10156449120
domain: 1
receive_time: 2017/11/26 14:10:08
serial: 007901004140
seqno: 10156449120
答案 1 :(得分:2)
您可以使用SAX Streams获取xml元素的内部文本内容。 SAX是解析xml的更好方法,无需将整个XML读入内存即DOM Python SAX