1

I have been trying to convert list data to xml file.

But getting below error : ValueError: Invalid tag name '0'

This is my header : 'Name,Job Description,Course'

Code:

import pandas as pd

lst = [ 'Name,Job Description,Course' , 
   'Bob,Backend Developer,MCA',  
   'Raj,Business Analyst,BMS', 
   'Alice,FullStack Developer,CS' ]

df = pd.DataFrame(lst)
with open('output.xml', 'w') as myfile: 
  myfile.write(df.to_xml())
3
  • The format of your data isn't proper. Your df has lst indices as keys and to_xml is trying to create XML using key value(s) pairs. Hence it tried taking 0 as tag name for the first entry. Commented Jun 5, 2022 at 8:40
  • You can refer the examples here and update your issue pandas.pydata.org/docs/reference/api/… Commented Jun 5, 2022 at 8:41
  • @kiric8494 your dataframe doesn't have columns names, which will be used to make the tag names; so declare columns, e.g. like : df = pd.DataFrame(data=lst,columns=header_data) Commented Jun 5, 2022 at 8:57

1 Answer 1

4

The df you created is improper. There are two scenarios.

  1. If you took name, job description, course as single header. You will fail at the point of saving df to xml.
  2. In order to save df as xml there is a format that need to be followed.

Below solution works. Hope this is what you are trying to achieve.

import pandas as pd

lst = [ ['Name','Job_Description','Course'] , 
['Bob','Backend Developer','MCA'],  
['Raj','Business Analyst','BMS'], 
['Alice','FullStack Developer','CS'] ]

df = pd.DataFrame(lst[1:], columns=[lst[0]])
print(df)
df.to_xml('./output.xml')
Sign up to request clarification or add additional context in comments.

2 Comments

: Can you elaborate more on step : pd.DataFrame(lst[1:], columns=[lst[0]])
From your query I understood that Name, job description, Course are headers. So while creating the DataFrame I have mentioned these values as column names using variable columns. The remaining data in lst i.e. lst[1:] is appended under the respective columns. For better understanding of creating DataFrame refer : pandas.pydata.org/docs/reference/api/pandas.DataFrame.html

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.