kade

技術系の記事を書いていきます。

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/

初めてのPython 第3版

初めてのPython 第3版