I have a XML file with some Tree structure, elements, attributes, text. I need to use the this XML as template (tree structure and tags) and create another XML, which might not have same number of elements (i.e. In below template there are two 'column' element, but the one I want to create has three elements 'column').
Below is the XML I want to use as template
<custom-data>
<schema>SCHEMA</schema>
<columns>
<column>
<name>ORGANIZATION</name>
<datatype>NUMBER</datatype>
<length/>
<precision>18</precision>
<not-null>Yes</not-null>
</column>
<column>
<name>LOCATION</name>
<datatype>NUMBER</datatype>
<length/>
<precision>18</precision>
<not-null>Yes</not-null>
</column>
</columns>
</custom-data>
Instead of defining a similar tree using lxml by defining Each element one by one as below. For example if 'df' is my pandas dataframe with data. which has columns as (Target Column, Data Type , Length, Scale, Nullable._
Target Column Data Type Length Scale Nullable
COLUMN1 NUMBER 38 0 N
COLUMN2 NUMBER 38 0 N
COLUMN3 NUMBER 38 0 N
Below is the sample python code I am using
from lxml import etree as et
root = et.Element('custom-data')
schema= et.SubElement(root, 'schema')
schema.text='SCHEMA'
columns= et.SubElement(root, 'columns')
for row in df.iterrows():
column = et.SubElement(columns, 'columns')
name = et.SubElement(column , 'name')
datatype = et.SubElement(column , 'datatype')
length = et.SubElement(column , 'length')
precision = et.SubElement(column , 'precision')
notnull = et.SubElement(column , 'not-null')
name.text = str(row[1]['Target Column'])
datatype.text = str(row[1]['Data Type'])
length.text = str(row[1]['Length'])
precision.text = str(row[1]['Scale'])
notnull.text = str(row[1]['Nullable'])
xml_test=et.tostring(root, pretty_print=True).decode('utf-8')
f=open("xml_test.xml", "w")
f.write(xml_test)
Expected output is
<custom-data>
<schema>SCHEMA</schema>
<columns>
<column>
<name>COLUMN1</name>
<datatype>NUMBER</datatype>
<length>38</length>
<precision>0</precision>
<not-null>N</not-null>
</column>
<column>
<name>COLUMN2</name>
<datatype>NUMBER</datatype>
<length>38</length>
<precision>0</precision>
<not-null>N</not-null>
</column>
<column>
<name>COLUMN3</name>
<datatype>NUMBER</datatype>
<length>38</length>
<precision>0</precision>
<not-null>N</not-null>
</column>
</columns>
</custom-data>
How can I leverage the structure given in the Sample XML, so that I dont need to define it again in my code. Any simpler method?