Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • Example XML block:

**

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

**

  • Code snippet:

**

    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()
like image 966
user1052620 Avatar asked Oct 10 '22 10:10

user1052620


1 Answers

subelement.getchildren()

or

for subelement in rootElement:
    ...
    for subsub in subelement:
        print subsub.tag
like image 119
Steven D. Majewski Avatar answered Oct 13 '22 11:10

Steven D. Majewski