如何使用python解析嵌套的XML标签? [英] How do you parse nested XML tags with python?

查看:399
本文介绍了如何使用python解析嵌套的XML标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用了错误的术语,请原谅,但这是我想要实现的目标。我正在尝试从嵌套标签中提取属性和文本信息,例如别名,付款,金额等。但是,我的示例代码块只能从。子中的子元素中提取信息,而不能从任何子元素中提取信息。

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 .

如何使用elementtree尝试获取子元素的子元素?一次,如果我使用不当,请原谅我的术语:
**

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


  • 示例XML块:

**

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


推荐答案

subelement.getchildren()

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

这篇关于如何使用python解析嵌套的XML标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆