3

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

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thx for the quick answer, however I need only the application tags on a specific level. I think I can do it some other less elegant way. For example only the application name, protocols and ports for apps on level 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.