How do you parse nested XML tags with python?

那年仲夏 提交于 2019-12-06 03:36:18

问题


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

回答1:


subelement.getchildren()

or

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


来源:https://stackoverflow.com/questions/8186343/how-do-you-parse-nested-xml-tags-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!