我的xml文件是这样的:
<root>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</catalog>
</root>
我需要没有根节点的输出,如下所示:
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
</catalog>
我可以删除元素。但我不知道如何使用python只删除根节点。任何人都可以帮我这个吗?
答案 0 :(得分:2)
在你的情况下足以使用list来获得第一个元素:
>>> s="""<root>
>>> ...
>>> """
>>> import xml.etree.ElementTree as ET
>>> catalog = list( ET.fromstring(s) )[0] #<--- here
>>> ET.tostring(catalog, encoding='utf8', method='xml')