Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save an etree xml object? saving loading lxml etree objects issue

Tags:

python

lxml

I have a etree object called projectxml:

projetxml type <type 'lxml.etree._Element'>

I need to save it on disk, so I convert it to element tree:

savedxml=et.ElementTree(projetxml)
savedxml.write('/home/simon/Vysis.xml')

An other script had to load the the Vysis.xml and two other files of the same kind:

vysis=et.parse('/home/simon/Vysis.xml')
asi=et.parse('/home/simon/ASI.xml')
psi=et.parse('/home/simon/PSI.xml')

Now asi, psi and vysis lxml objects are of the type for example:

<lxml.etree._ElementTree object at 0xa7eaf8c>

My problem is that I can no more do:

R=et.Element('DataBase')
R.append(asi)
R.append(psi)
R.append(vysis)

because of the error:

R.append(asi)
  File "lxml.etree.pyx", line 697, in lxml.etree._Element.append (src/lxml  /lxml.etree.c:35471)
TypeError: Argument 'element' has incorrect type (expected lxml.etree._Element, got lxml.etree._ElementTree)

I suppose I have two solutions. The first one could be to avoid to convert etree.Element to etree.ElementTree and to save it "directly", but I don't know how. The second solution would be to back convert etree.ElementTree to etree.Element type...There should be a clean solution to save/load a xml object?

like image 383
Jean-Pat Avatar asked May 14 '12 10:05

Jean-Pat


People also ask

What is Etree in lxml?

lxml. etree supports parsing XML in a number of ways and from all important sources, namely strings, files, URLs (http/ftp) and file-like objects. The main parse functions are fromstring() and parse(), both called with the source as first argument.

Is XML and lxml are same?

lxml is a Python library which allows for easy handling of XML and HTML files, and can also be used for web scraping. There are a lot of off-the-shelf XML parsers out there, but for better results, developers sometimes prefer to write their own XML and HTML parsers.

Is lxml default in Python?

It almost is. lxml is not written in plain Python, because it interfaces with two C libraries: libxml2 and libxslt.


1 Answers

The parse function returns an ElementTree, not an Element. If you want to use the results of parse as elements, you need to call getroot.

vysis=et.parse('/home/simon/Vysis.xml').getroot()
asi=et.parse('/home/simon/ASI.xml').getroot()
psi=et.parse('/home/simon/PSI.xml').getroot()

R=et.Element('DataBase')
R.append(asi)
R.append(psi)
R.append(vysis)
like image 193
Kris Harper Avatar answered Oct 14 '22 01:10

Kris Harper