How to add a root inside of main root of XML in Pyton

Question:

I have the following xml which i have export using the following:

df.to_xml('test.xml', index=False, row_name='instance', root_name='file')

which produces an xml file like:

<file>
  <instance>
    <ID>1</ID>
    <name>John</name>
    <age>32</age>
    <city>London</city>
  </instance>
....
</file>

How can i add an extra root (<NAMES>) for underneath <file> so my output is below:

<file>
<NAMES>
  <instance>
    <ID>1</ID>
    <name>John</name>
    <age>32</age>
    <city>London</city>
  </instance>
....
</NAMES>
</file>
Asked By: SOK

||

Answers:

Add ‘Files’ as subelement to the root and to save it you can use standard file object.

import xml.etree.ElementTree as ET
root = ET.fromstring(df.to_xml(index=False, row_name='instance', root_name='file'))
file = ET.Element("file")
files = ET.SubElement(file, 'Files')
for e in root:
  files.append(e)
f = open('test.xml','w')
f.write(ET.tostring(file))
Answered By: Surjit Samra

Pandas XML IO does support XSLT 1.0 (the special-purpose language to transform XML files) for to_xml. See docs using the stylesheet argument which is only support by the default lxml parser (which you do use).

Below XSLT runs the identity transform to copy document as is then re-styles the <file> node to add a child <NAMES> element:

strXSLT = """
<xsl:stylesheet version="1.0" , 
    root_name = 'file',
    stylesheet = strXSLT
)
Answered By: Parfait
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.