1

我是 python 新手,所以感谢您的帮助。我有一个类似于

  <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>父级中。如果存在,则打印该值,如果不存在,则打印 msg "no ip record"

输出应该是这样的:

name= customer1
ip= 11.12.13.4/32

name=customer2
ip= No ip record. 

我怎样才能在python中得到这个?

4

1 回答 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
于 2014-04-08T02:30:21.090 回答