Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating xml in python and lxml

Tags:

python

xml

lxml

I have this xml from sql, and I want to do the same by python 2.7 and lxml

<?xml version="1.0" encoding="utf-16"?>
<results>
  <Country name="Germany" Code="DE" Storage="Basic" Status="Fresh" Type="Photo" />
</results>

Now I have:

from lxml import etree

# create XML 
results= etree.Element('results')

country= etree.Element('country')
country.text = 'Germany'
root.append(country)



filename = "xmltestthing.xml"
FILE = open(filename,"w")
FILE.writelines(etree.tostring(root, pretty_print=True))
FILE.close()

Do you know how to add rest of attributes?

like image 326
user278618 Avatar asked Dec 17 '10 11:12

user278618


2 Answers

Note this also prints the BOM

>>> from lxml.etree import tostring
>>> from lxml.builder import E
>>> print tostring(
             E.results(
                 E.Country(name='Germany',
                           Code='DE',
                           Storage='Basic',
                           Status='Fresh',
                           Type='Photo')
             ), pretty_print=True, xml_declaration=True, encoding='UTF-16')

��<?xml version='1.0' encoding='UTF-16'?>
<results>
  <Country Status="Fresh" Type="Photo" Code="DE" Storage="Basic" name="Germany"/>
</results>
like image 182
Marco Mariani Avatar answered Oct 19 '22 05:10

Marco Mariani


Save to XML file

doc.write('output.xml', xml_declaration=True, encoding='utf-16') 

instead of:

outFile = open('output.xml', 'w')

doc.write(outFile, xml_declaration=True, encoding='utf-16') 
like image 22
Habib Avatar answered Oct 19 '22 04:10

Habib