我有一个要求,我需要解析xml,并且需要将整个内容捕获到字符串中。我尝试使用迷你,这是可行的。请帮助通过元素树实现这一目标
.XML:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
迷你实例:
from xml.dom import minidom
xmldoc = minidom.parse(country.xml)
print xmldoc.toxml()
但是,当我使用它时,元素树不确定如何实现这一点:到目前为止我的代码
import xml.etree.ElementTree as etree
tree = etree.parse('C:\Users\Administrator\Desktop\country.xml')
print tree.getroot() *This is not working*
您可以使用 etree.tostring()
从 ElementTree 树生成字符串:
print etree.tostring(tree.getroot())