To deploy an excellent answer on Victor (and slightly tweak it to work with duplicate columns), you can set it as the to_xml DataFrame method:
def to_xml(df, filename=None, mode='w'): def row_to_xml(row): xml = ['<item>'] for i, col_name in enumerate(row.index): xml.append(' <field name="{0}">{1}</field>'.format(col_name, row.iloc[i])) xml.append('</item>') return '\n'.join(xml) res = '\n'.join(df.apply(row_to_xml, axis=1)) if filename is None: return res with open(filename, mode) as f: f.write(res) pd.DataFrame.to_xml = to_xml
Then you can print xml:
In [21]: print df.to_xml() <item> <field name="field_1">cat</field> <field name="field_2">15,263</field> <field name="field_3">2.52</field> <field name="field_4">00:03:00</field> </item> <item> ...
or save it in a file:
In [22]: df.to_xml('foo.xml')
Obviously, this example needs to be modified in accordance with the xml standard.
source share