[Solved] Parse XML to Table in Python


I’ve got the needed outcome using following script.

XML File:

<?xml version="1.0" encoding="UTF-8"?>
<base>
  <element1>element 1</element1>
  <element2>element 2</element2>
  <element3>
    <subElement3>subElement 3</subElement3>
  </element3>
</base>

Python code:

import pandas as pd
from lxml import etree

data = "C:/Path/test.xml"

tree = etree.parse(data)

lstKey = []
lstValue = []
for p in tree.iter() :
    lstKey.append(tree.getpath(p).replace("https://stackoverflow.com/",".")[1:])
    lstValue.append(p.text)

df = pd.DataFrame({'key' : lstKey, 'value' : lstValue})
df.sort_values('key')

Result:

Python result

solved Parse XML to Table in Python