Python中对XML节点的字符串操作
我正在读取一个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
我该如何解析每个节点,并对它们进行一些字符串操作呢?
1 个回答
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 格式的字符串。如果你想要 text
属性,直接使用 a.text
就可以了。