Parse XML to Table in Python -


i'm trying parse xml table-like structure in python. imagine xml this:

<?xml version="1.0" encoding="utf-8"?> <base>   <element1>element 1</element1>   <element2>element 2</element2>   <element3>     <subelement3>subelement 3</subelement3>   </element3> </base> 

i'd have result this:

key                       | value base.element1             | "element 1" base.element2             | "element 2" base.element3.subelement3 | "subelement 3" 

i've tried using xml.etree.celementtree, functions described here how convert xml string dictionary in python?

is there function can this? answers found written particular xml schemes , need edited each new xml scheme. reference, in r it's easy xml , xml2 packages , xmltolist function.

i've got 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 pd lxml import etree  data = "c:/path/test.xml"  tree = etree.parse(data)  lstkey = [] lstvalue = [] p in tree.iter() :     lstkey.append(tree.getpath(p).replace("/",".")[1:])     lstvalue.append(p.text)  df = pd.dataframe({'key' : lstkey, 'value' : lstvalue}) df.sort_values('key') 

result:

python result


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -