Home > database >  how to insert data into a template.xml
how to insert data into a template.xml

Time:10-09

I have a xml form that I would like to be filled in automatically. It is something like this

<?xml version="1.0" encoding="UTF-8"?>
<Tag1>
    <Tag1.1>10001116-01</Tag1.1>
    <Tag1.2>50</Tag1.2>
    <Tag1.3>10001116</Tag1.3>
    <Tag1.4>
        <Tag1.4.1>
            <Tag1.4.2>123456</Tag1.4.2>
        </Tag1.4.1>
    </Tag1.4>
    <Tag1.5/>
</Tag1>

If I have this XML in a file template.xml And have another file like "Usecase1" where I say something like

Tag1.1= XXX
Tag1.4.2= XXX

change the XXX with numbers or words that I want, and the values will be inserted into my template.xml automatically. At the end, I want to copy the template and paste it. I know I can do this with Excel, but is there not another way? Thank you.

CodePudding user response:

Create a template.xml file and then in your code you could replace the values and create a new xml file.

Example:

import xml.etree.ElementTree as ET

if __name__ == "__main__":
    tag_1_1 = "XXX"
    tag_1_4_2= "XXX"
    tree = ET.parse('template.xml')
    tree.find(".//Tag1.1").text = tag_1_1
    tree.find(".//Tag1.4.2").text = tag_1_4_2
    tree.write("output.xml")
  • Related