繁体   English   中英

如何使用python从xml文件中删除根元素?

[英]How to remove root element from xml file using python?

我有这样的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仅删除根节点。 谁能帮我这个 ?

您的情况足以使用list获取第一个元素:

>>> s="""<root>
           <catalog>
             <book id="bk101">
             ...
    """
>>> import xml.etree.ElementTree as ET
>>> catalog = list( ET.fromstring(s) )[0]  #<--- here
>>> ET.tostring(catalog, encoding='utf8', method='xml')

或使用迭代器

>>> catalog = next( ET.fromstring(s).iter() )  #<--- here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM