<breakfast_menu> <food> <name>Belgian Waffles</name> <price>$5.95</price> <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description> <calories>650</calories> </food> <food> <name>Strawberry Belgian Waffles</name> <price>$7.95</price> <description>Light Belgian waffles covered with strawberries and whipped cream</description> <calories>900</calories> </food> <food> <name>Berry-Berry Belgian Waffles</name> <price>$8.95</price> <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description> <calories>900</calories> </food> <food> <name>French Toast</name> <price>$4.50</price> <description>Thick slices made from our homemade sourdough bread</description> <calories>600</calories> </food> <food> <name>Homestyle Breakfast</name> <price>$6.95</price> <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description> <calories>950</calories> </food> </breakfast_menu>
なので、正しくrootが取得できています。
また、先程のrootはイテレート可能な子ノードを持ちます。
1 2 3 4 5 6 7 8
>>> for child in root: ... print(child.tag, child.attrib) ... food {} food {} food {} food {} food {}
上から構造化データを辿っていくことが可能です。
データ構造を調査する
上記の例で言うと、foodの下の階層の要素がわからない場合はどうしたらよいでしょうか?
そう言った場合は先程のrootと同じように以下のようにすると下の階層の要素のtagがわかります。
1 2 3 4 5 6 7 8
>>> foods = root.findall('food') >>> for e in foods[0]: ... print(e.tag) ... name price description calories