解析elementTree以返回XML格式的字符串 - Python

时间:2014-06-09 21:01:21

标签: python xml string elementtree

有没有办法从文件中解析整个ElementTree并将其作为python中的字符串返回?我想将整个文件读入单个字符串值,例如抓取dump(tree)的整个输出?任何帮助或建议将不胜感激!

XML

import xml.etree.ElementTree as ET

print "Enter a filename"
filename = input()
tree = ET.parse(filename)
string = tree.tostring() ##is there a way to do something like this?

的test.xml

<data>

     <serial>

     <serial name = "serial">SN001</serial>

     </serial>

     <items>

    <item>Test1 = Failed</item>

    <item>Test2 = Passed</item>

    <item>Test3 = Passed</item>

      </items>

</data>

1 个答案:

答案 0 :(得分:0)

tostring是模块函数,而不是方法。

string = ET.tostring(tree.getroot())