【问题标题】:Python-xml: Verify child element exist for every parent instancePython-xml:验证每个父实例是否存在子元素
【发布时间】:2014-04-08 02:23:02
【问题描述】:

我是 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>

我需要检查每个实例以验证标签是否存在于每个&lt;detail&gt; 父级中。如果存在,则打印该值,如果不存在,则打印 msg "no ip record"

输出应该是这样的:

name= customer1
ip= 11.12.13.4/32

name=customer2
ip= No ip record. 

我如何在 python 中得到这个?

【问题讨论】:

标签: python xml parsing tags get-childitem


【解决方案1】:

这是使用标准库中的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

【讨论】:

  • 完美运行!谢谢!!
猜你喜欢
  • 1970-01-01
  • 2020-11-20
  • 2014-07-07
  • 1970-01-01
  • 2018-11-15
  • 2017-01-25
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多