How to create Pandas DataFrame from nested XML?
In this article, we will learn how to create Pandas DataFrame from nested XML. We will use the xml.etree.ElementTree module, which is a built-in module in Python for parsing or reading information from the XML file. The ElementTree represents the XML document as a tree and the Element represents only a single node of the tree.
Here, we will use some functions to process out code which is stated below:
- ElementTree.parse( XML_file) : To read data from an XML file
- root.iter(‘root_name’): To iterate through the branches of the root node
- ElementTree.fromstring(XML_file) : To read data when XML code which is passed as a string inside triple quotes in the python code
- prstree.findall(‘store’): To find all the elements of the parsed XML ElementTree
- node.attribute.get(attribte_name ): To get the attribute
- node.find(attribte_name): To retrieve the text content of the mentioned attribute_name
- pandas.DataFrame() : To convert the XML data to a DataFrame
- list.append(): To append the items to a list
- Parse or read the XML file using ElementTree.parse( ) function and get the root element.
- Iterate through the root node to get the child nodes attributes ‘SL NO’ (here) and extract the text values of each attribute (here foodItem, price, quantity, and discount).
- Get the respective food items with specifications as a unit appended to a list(here all_items() list).
- Convert the list into a DataFrame using pandas.DataFrame() function and mention the column names within quotes separated by commas.
- Print the DataFrame and it’s done.
Input Nested XML Data
In this code below we have parsed the XML file. Give the complete path where you have saved the XML file within quotes. So here we need to use ElementTree.parse() function to read the data from the XML file and then the getroot() function to get the root. Then follow the steps given.
Note: The XML file should be saved in the same directory or folder where your Python code saved.
We can also pass the XML content as a string inside triple quotes. In that case, we need to use the fromstring() function to read the string. Get the root using the ‘tag’ object and follow the same steps to convert it to a DataFrame as mentioned above.