Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python XML parsing on different levels

Tags:

python

xml

I am trying to use Python to parse an XML with the same name tags on different levels. I searched a lot trough the documentation and other StackOverflow answers but I couldn't find a suitable solution.

The XML looks like this:

<configuration>
   <applications>
      <application>
         <name>name1</name>
         <protocol>protocol1</protocol>
         <port>port1</port>
      </application>
      <application>
          .
      </application>
   <application-set>
      <name>appset_name1</name>
      <application>
         <name>appname1</name>
      </application>
   </application-set>
   <application-set>
      .
   </application-set>
   </applications>
</configuration>

I need to take the name, protocol and port from the application tag on 3rd level and name and other application name from the application-set tag on the 3rd level (could be in a simple list)

Thx

like image 782
user2232414 Avatar asked May 01 '26 08:05

user2232414


1 Answers

With the ElementTree API you simply look for the .//application XPath to find <application> elements at any level:

for application in tree.findall('.//application'):
    name = application.find('name').text
    protocol = application.find('protocol')
    if protocol is not None:
        protocol = protocol.text
    port = application.find('port')
    if port is not None:
        port = port.text

XPath expressions can find you the tag on more specific levels too, by specifying the applicable parents:

'.//applications/application'     # any <application> tag below <applications>
'.//application-set/application'  # any <application> tag below <applications>
'./*/*/application'                 # <application> tags with two elements in between
like image 147
Martijn Pieters Avatar answered May 03 '26 22:05

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!