Frage

I am new to python so I appreciate your help. I have an xml code similar to

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

What I need is to check every instance of to verify whether or not the tag exists in every <detail> parent. If it exists then print the value and if not then print the msg "no ip record".

The output should be something like this:

name= customer1
ip= 11.12.13.4/32

name=customer2
ip= No ip record. 

How I can get this in python?

War es hilfreich?

Lösung

Here's a solution using xml.etree.ElementTree from the standard library:

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)

prints:

name=customer1, ip=11.12.13.4/32
name=customer2, ip=No ip record
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top