appending xml node with subnodes of sam name

Question:

I have key-value pairs: task_vars = '{"BNS_DT": "20220831","DWH_BD": "dwh_bd=2022-08-31","LAYR_CD": "STG"}'

with which I would like to generate subnodes variable: tsk_var = ET.fromstring("""<variable><name></name><value></value></variable>""")

and then append variables node in: payload = ET.fromstring("""<task-launch><variables></variables><name>{}</name></task-launch>""".format(task_name))

I loop though the key-values and try to append variables node:

tsk_vars = json.loads(task_vars)
for name, value in tsk_vars.items():
    for nm in tsk_var.iter('name'):
        nm.text = name
    for vl in tsk_var.iter('value'):
        vl.text = value
    print('to be added')
    print(ET.tostring(tsk_var))
    payload.find('variables').append(tsk_var)

When I print out the subnode by which variables should be appended I got correct values on each iteration. But in final result I get correct number of subnodes but all are filled with last key value:

<task-launch>
  <variables>
    <variable>
        <name>LAYR_CD</name>
        <value>STG</value>
    </variable>
    <variable>
        <name>LAYR_CD</name>
        <value>STG</value>
    </variable>
    <variable>
        <name>LAYR_CD</name>
        <value>STG</value>
    </variable>
 </variables>

Please hot do I get correct values for every variable subnode?

Asked By: JanFi86

||

Answers:

Try it this way:

destination = payload.find('.//variables')

# use f-strings to insert the values into the <variable> children
for name, value in tsk_vars.items():
    new_childs = ET.fromstring(f"""<variable><name>{name}</name><value>{value}</value></variable>""")
    destination.insert(0,new_childs)

#the line below requires python 3.9+
ET.indent(payload, space='  ', level=0)

print(ET.tostring(payload).decode())

Output:

<task-launch>
  <variables>
    <variable>
      <name>LAYR_CD</name>
      <value>STG</value>
    </variable>
    <variable>
      <name>DWH_BD</name>
      <value>dwh_bd=2022-08-31</value>
    </variable>
    <variable>
      <name>BNS_DT</name>
      <value>20220831</value>
    </variable>
  </variables>
</task-launch>
Answered By: Jack Fleeting
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.