带有 lxml 生成器的 SSS 版本
SSS version with lxml builder
我正在使用 lxml 构建器元素,我想知道如何更改 sss 版本?
我的代码如下,用于创建 .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)
这段代码给出了以下内容:
<?xml version='1.0' encoding='utf-8'?>
<sss>
<date>2021-03-03</date>
<user>username</user>
<survey>
<record ident="A">
但我们现在有 sss version='1.2',甚至是 2.0。是否可以设置版本?
您可以使用字典添加属性。这是一个简化的例子:
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)
输出:
<sss version="2.0">
<date>2021-03-03</date>
<user>John Doe</user>
</sss>
我正在使用 lxml 构建器元素,我想知道如何更改 sss 版本?
我的代码如下,用于创建 .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)
这段代码给出了以下内容:
<?xml version='1.0' encoding='utf-8'?>
<sss>
<date>2021-03-03</date>
<user>username</user>
<survey>
<record ident="A">
但我们现在有 sss version='1.2',甚至是 2.0。是否可以设置版本?
您可以使用字典添加属性。这是一个简化的例子:
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)
输出:
<sss version="2.0">
<date>2021-03-03</date>
<user>John Doe</user>
</sss>