Priya
Priya

Reputation: 591

How to remove root element from xml file using python?

I have my xml file like this :

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

I need my output without root node as the following :

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

I am able to remove element. But I dont know how to remove only root node using python. Can anyone help me with this ?

Upvotes: 0

Views: 3311

Answers (1)

dani herrera
dani herrera

Reputation: 51705

In your case is enough to use list to get first element:

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

Or use the iterator:

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

Upvotes: 4

Related Questions