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("/",".")[1:])
lstValue.append(p.text)
df = pd.DataFrame({'key' : lstKey, 'value' : lstValue})
df.sort_values('key')
Result:

Medium
medium.com › @robertopreste › from-xml-to-pandas-dataframes-9292980b1c1c
From XML to Pandas dataframes. How to parse XML files to obtain proper… | by Roberto Preste | Medium
August 25, 2019 - We can think of this structure as a pandas DataFrame in which each student represents an observation, with its name attribute being the main identifier and the sub-elements being other features of the observation. A tabular representation of these data would be like this: So we want to find a way to convert XML-structured data to a more functional table. Given the structure of XML files, we can represent them as a tree, and this is the approach used by the xml.etree.ElementTree Python module.
python - How to convert XML to table? - Stack Overflow
How can I do the same thing using Python? TIA. ... I think you're looking for the Pandas library. See this answer: https://stackoverflow.com/a/45815394/10358386 ... That's somewhat helpful, but I would like to load some items, but not all, into a data frame. I'm really looking for something that gives me a little more control over which elements I'm loading into a data frame. Thanks. ... I know excel works perfect to convert xml to table ... More on stackoverflow.com
python - read xml file, convert it to table (dataframe) - Stack Overflow
this the first time I am dealing with xml file, so I am very lost. I would appreciate any help. All I want is to read the file and convert it to regular table (dataframe). I have file with this str... More on stackoverflow.com
Convert xml to excel/csv
Please help me in converting XML file into excel/csv. Thank you in advance. More on discuss.python.org
How to convert table into a specific XML format using Python? - Stack Overflow
How to convert a table from a database into a specific XML format request by client.I know this can be done in excel using XML mapping.But is there a way I can do using Python? More on stackoverflow.com
Videos
Top answer 1 of 4
1
Given the two levels of nodes that cover the Coluna attributes, consider XSLT, the special-purpose language designed to transform or style original XML files. Python's lxml can run XSLT 1.0 scripts and being the default parse to pandas.read_xml can transform your raw XML into a flatter version to parse to DataFrame.
XSLT (save as .xsl file, a special .xml file)
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:pace='http://www.ms.com/pace'>
<xsl:output method="xml" omit-xml-declaration="no" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- REDESIGN XML TO ONLY RETURN AnaliseDiaria NODES -->
<xsl:template match="/*">
<xsl:copy>
<xsl:apply-templates select="descendant::pace:AnaliseDiaria"/>
</xsl:copy>
</xsl:template>
<!-- REDESIGN AnaliseDiaria NODES -->
<xsl:template match="pace:AnaliseDiaria">
<xsl:copy>
<!-- BRING DOWN Produto ATTRIBUTES WITH CURRENT ATTRIBUTES -->
<xsl:copy-of select="ancestor::pace:Produto/@*|@*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Online Demo
Python
analise_diaria_df = pd.read("input.xml", stylesheet="style.xsl")
analise_diaria_df
# Coluna1 Coluna2 Coluna3 ... Coluna14 Coluna15 Coluna16
# 0 21-851611 CAMIO VO NaN ... NaN NaN NaN
# 1 21-3667984 SCA4X2 -1.0 ... NaN NaN NaN
# 2 21-3667994 SCA963 -1.0 ... NaN NaN NaN
# 3 21-3676543 SCA713 -1.0 ... NaN NaN NaN
# 4 21-3676601 SCA97 -1.0 ... NaN NaN NaN
# 5 21-3814014 CAMIX2 NaN ... NaN NaN NaN
# 6 21-3814087 SCA56 NaN ... NaN NaN NaN
# 7 21-3814087 SCA56 NaN ... 195.000,00 NF9 10203910A
# 8 21-3814087 SCA56 NaN ... 195.090,00 NaN NaN
# 9 21-3814087 SCA56 NaN ... 195.270,00 NaN NaN
# 10 21-3814087 SCA56 NaN ... 195.482,60 NaN NaN
# 11 21-3814087 SCA56 NaN ... 195.627,80 NaN NaN
# 12 21-3814087 SCA56 NaN ... 204.529,82 NaN NaN
# 13 21-3814087 SCA56 NaN ... NaN NaN 158PES
2 of 4
0
Fortunately, in the case of your xml in the question, you can use the pandas read_xml() method, although you'll have to skirt around the namespaces issue:
import pandas as pd
pd.read_xml(file.xml,xpath='//*[local-name()="Linha"]//*[local-name()="Produto"]')
Output:
Coluna1 Coluna2 Coluna3 Coluna4 Coluna5 {http://www.ms.com/pace}AnaliseDiaria
0 21-851611 CAMIO VO NaN NaN NaN NaN
1 21-3667984 SCA4X2 -1.0 NaN NaN NaN
2 21-3667994 SCA963 -1.0 NaN NaN NaN
etc. If you are not interested in one column or anothter, you can simply drop() it.
GeeksforGeeks
geeksforgeeks.org › python › convert-xml-structure-to-dataframe-using-beautifulsoup-python
Convert XML structure to DataFrame using BeautifulSoup - Python - GeeksforGeeks
March 21, 2024 - Now we have extracted the data from the XML file using the BeautifulSoup into the DataFrame and it is stored as ‘df’. To see the DataFrame we use the print statement to print it. ... # Python program to convert xml # structure into dataframes using beautifulsoup # Import libraries from bs4 import BeautifulSoup import pandas as pd # Open XML file file = open("gfg.xml", 'r') # Read the contents of that file contents = file.read() soup = BeautifulSoup(contents, 'xml') # Extracting the data authors = soup.find_all('author') titles = soup.find_all('title') prices = soup.find_all('price') pubdat
Refitsmarthomes
refitsmarthomes.org › wp-content › uploads › 2017 › 06 › ConvertToTables.html
ConvertToTables
January 12, 2024 - Foreign key fields are used to relate an object to its parent. The tables are saved in csv format. ... def create_tables(element,tables,FK_column,FK_value): """ A recursive function which travels through 'element' and its children. During the recursion, the 'tables' dictionary is populated with DataFrame tables - one for each element type """ name=element.tag.split('}')[1] if not name in tables.keys(): tables[name]=pd.DataFrame()#columns=attributes) d={} if not FK_column is None: d[FK_column]=FK_value for a in element.attrib.keys(): d[a]=element.get(a) tables[name]=tables[name].append(d,ignore_index=True) tables[name].index.name=name+'_PK' for child in element: create_tables(child,tables,name+'FK',tables[name].index.max()) tables={} create_tables(root,tables,None,None) for name in tables.keys(): tables[name].to_csv(name+'.csv')
CopyProgramming
copyprogramming.com › howto › parse-xml-to-table-in-python
Python: Python Code to Convert XML into a Table
August 2, 2023 - Converting XML into a Table: A Guide, Converting XML into Excel tables, Python Element Tree: Use XML to Generate Sub Tables in Excel Sheet
GitHub
github.com › knadh › xmlutils.py
GitHub - knadh/xmlutils.py: Python scripts for processing XML documents and converting to SQL, CSV, and JSON [UNMAINTAINED]
Convert an XML document to an SQL file. xml2sql --input "samples/fruits.xml" --output "samples/fruits.sql" --tag "item" --table "myfruits"
Starred by 255 users
Forked by 141 users
Languages Python 100.0% | Python 100.0%
PyPI
pypi.org › project › sql-xml-table
sql-xml-table
September 7, 2017 - JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
E-iceblue
cdn.e-iceblue.com › Tutorials › Python › Spire.XLS-for-Python › Program-Guide › Conversion › convert-xml-to-csv-in-python.html
How to Convert XML to CSV in Python: A Complete Guide
A robust converter must be able to handle these differences and map hierarchical XML into a flat, tabular CSV format. To load and parse an XML file in Python, you can use the built-in xml.etree.ElementTree library. This library lets you navigate the XML tree, retrieve elements, and access attributes.
Table Convert
tableconvert.com › home › convert xml to pandas dataframe online
Convert XML to Pandas DataFrame Online - Table Convert
October 16, 2021 - Generated code can be directly executed in Python environment for data analysis and processing. Extract tables from any website with one click. Convert to 30+ formats including Excel, CSV, JSON instantly - no copy-pasting required. Converting XML to PandasDataFrame?
GeeksforGeeks
geeksforgeeks.org › parsing-tables-and-xml-with-beautifulsoup
Parsing tables and XML with BeautifulSoup - GeeksforGeeks
October 8, 2025 - Scraping is a very essential skill that everybody should learn, It helps us to scrap data from a website or a file that can be used in another beautiful manner by the programmer. In this article, we will learn how to extract tables with beautiful soup and XML from a file. Here, we will scrap data using the Beautiful Soup Python Module.
Stack Overflow
stackoverflow.com › questions › 59635922 › how-to-convert-table-into-a-specific-xml-format-using-python
How to convert table into a specific XML format using Python? - Stack Overflow
Please take a look at the python standard library xml: https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree ... Sign up to request clarification or add additional context in comments.
