0

i have a real (and maybe pretty stupid) problem to convert a xml-file into a dataframe from pandas. Im new in python and need some help. I trying a code from another thread and modificate it but it not works.

I want to iterate through this file:

<objects>
 <object id="123" name="some_string">
<object>
  <id>123</id>
  <site id="456" name="somename" query="some_query_as_string"/>
  <create-date>some_date</create-date>
  <update-date>some_date</update-date>
  <update-user id="567" name="User:xyz" query="some_query_as_string"/>
  <delete-date/>
  <delete-user/>
  <deleted>false</deleted>
  <system-object>false</system-object>
  <to-string>some_string_notifications</to-string>
</object>
<workflow>
  <workflow-type id="12345" name="WorkflowType_some_workflow" query="some_query_as_string"/>
  <validated>true</validated>
  <name>somestring</name>
  <exported>false</exported>
</workflow>

Here is my code:

import xml.etree.ElementTree as ET
import pandas as pd

path = "C:/Users/User/Desktop/test.xml"
with open(path, 'rb') as fp:
    content = fp.read()
parser = ET.XMLParser(encoding="utf-8")
tree = ET.fromstring(content, parser=parser)

def xml2df(tree):
root = ET.XML(tree)
all_records = []
for i, child in enumerate(root):
    record ={}
    for subchild in child:
        record[subchild.tag] = subchild.text
        all_records.append(record)
    return pd.DataFrame(all_records) 

Where is the problem? Please help :O

1 Answer 1

1

You are passing the file location string to ET.fromstring(), which is not the actual contents of the file. You need to read the contents of the file first, then pass that to ET.fromstring().

path = "C:/Users/User/Desktop/test.xml"
with open(path, 'rb') as fp:
    content = fp.read()

parser = ET.XMLParser(encoding="utf-8")
tree = ET.fromstring(content, parser=parser)
Sign up to request clarification or add additional context in comments.

2 Comments

It indicates a raw string input. In this case it is not necessary; I will remove it.
Well now he cant find the file and i get a FileNotFoundError. I edited the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.