user1052620
user1052620

Reputation: 51

How do you parse nested XML tags with python?

Please excuse me if I'm using the wrong terminology, but here's what I'm trying to accomplish. I'm trying to pull attribute and text information from nested tags in such as alias, payment, amount, and etc... However my example code block is only able to pull info from and not anything from the subelements in .

How do I go about using elementtree to try and get to the subelements of my subelements? Once please excuse my terminology if I'm using it incorrectly: **

**

<root>
   <host name="comp1">
      <alias>smith_laptop</alias>
      <ipAddr>102.168.1.1</ipAddr>
      <owner>Mr_Smith</owner>
      <payment type="credit">
        <card type="Master Card"/>
        <amount>125.99</amount>
        <cardOwner name="John Smith"/>
        <expiration date="Oct 24"/>
      </payment>
   </host>

   <host name="comp2">
      <alias>matt_laptop</alias>
      <ipAddr>102.168.1.2</ipAddr>
      <owner>Mr_Mat</owner>
      <payment type="cash">
        <amount>100.00</amount>
      </payment>
   </host>
</root>

**

**

    import os
    from xml.etree import ElementTree as ET

    def main():

        rootElement = ET.parse("text.xml").getroot()

        for subelement in rootElement:
            print "Tag: ",subelement.tag
            print "Text: ",subelement.text
            print "Aribute:",subelement.attrib,"\n"
            print "Items:",subelement.items(),"\n"

    if __name__ == "__main__":
        main()

Upvotes: 5

Views: 9424

Answers (1)

Steven D. Majewski
Steven D. Majewski

Reputation: 2157

subelement.getchildren()

or

for subelement in rootElement:
    ...
    for subsub in subelement:
        print subsub.tag

Upvotes: 4

Related Questions