Search code examples
python-2.7lxmltriples

SSS version with lxml builder


I am using lxml builder Element, and I was wondering how I can change the sss version?

My code is the following for creating the .xml:

import lxml.etree
import lxml.builder

new_xml = lxml.builder.ElementMaker()
sss = new_xml.sss
date = new_xml.date
user = new_xml.user
survey = new_xml.survey
record = new_xml.record
variable = new_xml.variable
name = new_xml.name
label = new_xml.label

today_date=date.today().strftime('%Y-%m-%d') #today's date
uniq_list = ['a','b','c']
labels = ['a','b','c']
nvars = len(uniq_list)

for i in range(nvars):
    final_xml = (sss(
            date(today_date),
            user(username),
            survey(record(
                    *[variable(
                            name(uniq_list[i]),
                            label(labels[i]),
                            ident = str(i+1))
                     for i in range(nvars)],ident = 'A'))))
        
newxml = lxml.etree.tostring(final_xml, xml_declaration=True, encoding='utf-8', pretty_print=True)
with open(path+r"/"+stage+'_'+str(today_date)+'.xml','w') as myfile:
    myfile.write(newxml)

This code gives me the following:

<?xml version='1.0' encoding='utf-8'?>
<sss>
  <date>2021-03-03</date>
  <user>username</user>
  <survey>
    <record ident="A">

but we now have sss version='1.2', even 2.0. Is it possible to set a version?


Solution

  • You can add the attribute with a dictionary. Here is a simplified example:

    import lxml.etree
    import lxml.builder
     
    new_xml = lxml.builder.ElementMaker()
    sss = new_xml.sss
    date = new_xml.date
    user = new_xml.user
     
    final_xml = sss({"version": "2.0"},
                 date("2021-03-03"),
                 user("John Doe")
                )
    
    lxml.etree.dump(final_xml, pretty_print=True)
    

    Output:

    <sss version="2.0">
      <date>2021-03-03</date>
      <user>John Doe</user>
    </sss>