2011-11-14 5 views
0

xmlファイルを読み込んでいて、ノードのコンテンツに対して文字列操作を実行したいとします。Pythonのxmlノードでの文字列操作

import os 
import elementtree.ElementTree as ET 
from xml.etree.ElementTree import ElementTree 
from xml.etree.ElementTree import tostring 

xml_file = os.path.abspath(__file__) 
xml_file = os.path.dirname(xml_file) 
xml_file = os.path.join(xml_file, "Small1Review.xml") 
print xml_file 

root = ET.parse(xml_file).getroot() 
text = tostring(root) 
#print text 

for a in text: 
    #print a, "-->", a.text 
    text = tostring(a) 
    print text 

しかし、コードは次のエラーを与える、

Traceback (most recent call last): 
    File "myEtXML.py", line 33, in <module> 
    text = tostring(a) 
    File "C:\Python26\lib\xml\etree\ElementTree.py", line 1009, in tostring 
    ElementTree(element).write(file, encoding) 
    File "C:\Python26\lib\xml\etree\ElementTree.py", line 543, in __init__ 
    assert element is None or iselement(element) 
AssertionError 

は、どのように私は、各ノードを解析し、それらのそれぞれの上にいくつかの文字列操作を行うことができますか。?

答えて

2

for a in textと書いてありますが、textは文字列であり、XMLノードのように扱います。

tostringの方法はetree.Elementですが、この場合はaは文字列textの文字です。

ツリーを反復処理したい場合は、単にリスト

root = ET.parse(xml_file).getroot() 
for child in root: 
    print tostring(child) 

として扱う。また、コメント#print a, "-->", a.textはあなたのノードのtext属性をしたいことを示していると思われます。これはtostringメソッドによって返されるものではありません。 tostringメソッドはノードを受け取り、そこからXMLスタイルの文字列を作ります。テキスト属性が必要な場合は、a.textを使用してください。