Python-xml: 验证每个父元素的子元素是否存在
我刚开始学习Python,所以非常感谢你的帮助。我有一段类似这样的XML代码:
<ticket >
<device name="device1"/>
<detail>
<name>customer1</name>
<ip>11.12.13.4/32</ip>
<blob gid="20" lid="10"/>
</detail>
<classification>C1</classification>
</ticket>
<ticket >
<device name="device2"/>
<detail>
<name>customer2</name>
</detail>
<classification>C2</classification>
</ticket>
我需要做的是检查每一个实例,看看在每个<detail>
父标签里面是否存在<ip>
这个标签。如果存在,就打印出它的值;如果不存在,就打印消息"no ip record"
。
输出的结果应该像这样:
name= customer1
ip= 11.12.13.4/32
name=customer2
ip= No ip record.
我该怎么在Python中实现这个呢?
1 个回答
0
这里有一个使用标准库中的 xml.etree.ElementTree 的解决方案:
import xml.etree.ElementTree as ET
data = """
<root>
<ticket >
<device name="device1"/>
<detail>
<name>customer1</name>
<ip>11.12.13.4/32</ip>
<blob gid="20" lid="10"/>
</detail>
<classification>C1</classification>
</ticket>
<ticket >
<device name="device2"/>
<detail>
<name>customer2</name>
</detail>
<classification>C2</classification>
</ticket>
</root>"""
tree = ET.fromstring(data)
for ticket in tree.findall('.//ticket'):
name = ticket.find('.//name').text
ip = ticket.find('.//ip')
ip = ip.text if ip is not None else 'No ip record'
print "name={name}, ip={ip}".format(name=name, ip=ip)
输出结果是:
name=customer1, ip=11.12.13.4/32
name=customer2, ip=No ip record