简体   繁体   English

使用ElementTree解析XML中的子元素

[英]Parsing subchilds in XML with ElementTree

Im trying to extract information from a XML-document with ElementTree in Pyhton 3.2. 我试图在Pyhton 3.2中使用ElementTree从XML文档中提取信息。

The XML looks like this: XML如下所示:

<Page Id="1">
    <Group>4</Group>
    <Type>
        <Letter>B</Letter>
        <Number>101</Number>
        <Deep>
            <A>900</A>
            <B>900</B>
        </Deep>
    </Type>
</Page>

I manage to get the elementdata from "Group" with: 我设法从“组”中获取elementdata:

for Page in root.iter('Page'):
     Group = Page.find('Group').text

And "Letter"-data with: 和“字母”数据:

for Type in root.iter('Type'):
     Dim = Type.find('Letter').text

However I can't figure out how to get the data from the subchilds of "Deep" (A and B). 但是我不知道如何从“ Deep”(A和B)的子孩子那里获取数据。 All help is greatly appreciated! 非常感谢所有帮助!

You are very close. 你很亲密 Use find to find the Deep tag and the iterate over it. 使用find查找Deep标记并对其进行迭代。

Ex: 例如:

import xml.etree.ElementTree as ET
tree = ET.parse(filename)
root = tree.getroot()
for Type in root.iter('Type'):
    for deep_tag in Type.find("Deep"):
        print( deep_tag.text )

Output: 输出:

900
900

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

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