0

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?

owce
  • 67
  • 5
  • Are you asking how to add a `version` attribute? – mzjn Mar 03 '21 at 16:52
  • Yes, a version attribute. I mean that version 2.0 of Triple S allows some possibilities that version 1.0 doesn't. I didn't find a way to add it. I've put only part of the code as it is quite long - but if needed I can edit it. – owce Mar 03 '21 at 17:10
  • I've added lists so the code should work. – owce Mar 03 '21 at 17:21

1 Answers1

1

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>
mzjn
  • 48,958
  • 13
  • 128
  • 248