Python2.7: XMLを扱う -同名タグがある場合
前回xmlの要素へのアクセスをやりましたが、同名のタグがある場合にあのやり方だと引っ張って来れないので調べました。
sample.xml
<data> <child> <title>1番目</title> </child> <child> <title>2番目</title> <desc> <text>テキスト1</text> <text>テキスト2</text> <link>http://kade.hatenablog.com/</link> </desc> </child> </data>
このような場合に2番目のchild内のtitleを引っ張る場合
import xml.etree.ElementTree f = "sample.xml" etree = xml.etree.ElementTree.parse(f) root = etree.getroot() text = root[1].find("title").text.encode('utf_8') print text #2番目
この配列で子ノードを引っ張るやり方は混ぜて使うことも出来ます。
text = root[1].find("desc")[1].text.encode('utf_8') text2 = root[1].find("desc").find("link").text.encode('utf_8') print text # テキスト2 print text2 # http://kade.hatenablog.com/
- 作者: Mark Lutz,夏目大
- 出版社/メーカー: オライリージャパン
- 発売日: 2009/02/26
- メディア: 大型本
- 購入: 12人 クリック: 423回
- この商品を含むブログ (127件) を見る