【问题标题】:Python ElementTree xml content as string [duplicate]Python ElementTree xml内容作为字符串[重复]
【发布时间】:2015-02-02 18:28:06
【问题描述】:

我有一个要求,我需要解析 xml 并需要将整个内容捕获到字符串中。我尝试使用 minidom,它是可行的。请帮助通过 ElementTree 实现这一目标

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()

但是,当我使用它时 ElementTree 不确定如何实现:我的代码到目前为止

 import xml.etree.ElementTree as etree
 tree = etree.parse('C:\\Users\\Administrator\\Desktop\\country.xml')
 print tree.getroot() *This is not working*

【问题讨论】:

    标签: python xml elementtree minidom


    【解决方案1】:

    您可以使用etree.tostring() 从 ElementTree 树中生成字符串:

    print etree.tostring(tree.getroot())
    

    【讨论】:

      猜你喜欢
      • 2016-02-22
      • 2016-12-03
      • 2011-09-06
      • 2010-10-13
      • 1970-01-01
      • 2020-02-01
      • 2013-02-24
      • 2016-01-22
      • 1970-01-01
      相关资源
      最近更新 更多