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?
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.
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.
It almost is. lxml is not written in plain Python, because it interfaces with two C libraries: libxml2 and libxslt.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With