Python中xml节点上的字符串操作

Python中xml节点上的字符串操作,python,string,xml-parsing,Python,String,Xml Parsing,我正在读取一个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 =

我正在读取一个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
回溯(最近一次呼叫最后一次):
文件“myEtXML.py”,第33行,在
text=tostring(a)
文件“C:\Python26\lib\xml\etree\ElementTree.py”,第1009行,在tostring中
ElementTree(element).write(文件,编码)
文件“C:\Python26\lib\xml\etree\ElementTree.py”,第543行,在\uuu init中__
assert元素为None或iselement(元素)
断言错误

如何解析每个节点并对每个节点执行一些字符串操作?

您已经为in text编写了
,但是
text
是一个字符串,您将其视为XML节点

tostring
方法采用
etree.Element
,但在本例中,
a
是字符串
文本的一个字符

如果您想在树上迭代,只需将其视为一个列表

root = ET.parse(xml_file).getroot()
for child in root:
    print tostring(child)
此外,您的注释
#打印a,“-->”,a.text
似乎表明您需要节点的
text
属性。这不是
tostring
方法返回的内容。
tostring
方法获取一个节点并从中生成一个XML样式的字符串。如果需要text属性,只需使用
a.text