簡體   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