简体   繁体   English

你如何用python解析嵌套的XML标签?

[英]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? 如何使用elementtree尝试获取子元素的子元素? Once please excuse my terminology if I'm using it incorrectly: ** 如果我错误地使用它,请原谅我的术语:**

  • Example XML block: 示例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>

** **

  • 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()
subelement.getchildren()

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM