次のサンプル構成XMLファイルがあると仮定します。
<?xml version="1.0"?>
<note>
<to>Tove</to>
<infoaboutauthor>
<nestedprofile>
<aboutme>
<gco:CharacterString>I am a 10th grader who likes to play ball.</gco:CharacterString>
</aboutme>
</nestedprofile>
</infoaboutauthor>
<date>
<info_date>
<date>
<gco:Date>2003-06-13</gco:Date>
</date>
<datetype>
<datetype attribute="Value">
</datetype>
</datetype>
</info_date>
</date>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Pythonでは(ElementTreeを使用してみましたが、最適かどうかはわかりません)、特定のタグの特定の値を取得したいと思います。私が試してみました:
with open('testfile.xml', 'rt') as f:
tree = ElementTree.parse(f)
print 'Parsing'
root = tree.getroot()
listofelements = root_elem.findall('gco:CharacterString')
for elementfound in listofelements:
print elementfound.text
上記で使用したコードでは、次のエラーが発生するため、コロンがある場合は機能しないようです。
SyntaxError: prefix 'gco' not found in prefix map
私の目標は
- 「2003-06-13」タグのテキストを取得します
- 「aboutme」タグのテキスト
これを達成するための最良の方法は何ですか?親が「aboutme」と等しい「gco:CharacterString」を検索する方法はありますか?それとも、私が行くことができる口述にそれを入れるためのいくつかの便利な方法はありmydict['note']['to']['nestedprofile']['aboutme']
ますか?
注:「gco:」プレフィックスは、xmlの一部である私が処理しなければならないものです。elementtreeがこれに適していない場合、それは問題ありません。