简体   繁体   中英

Parsing subchilds in XML with ElementTree

Im trying to extract information from a XML-document with ElementTree in Pyhton 3.2.

The XML looks like this:

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

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). All help is greatly appreciated!

You are very close. Use find to find the Deep tag and the iterate over it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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