1

I have a string variable (xmlcontents) containing data which I want to convert it to xml I used fromstring function and changed the type from string to etree.ElementTree.Element type but I cant export it as a file can you help with exporting the variable myxml?

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(xmlcontents)
2
  • the code should work with, what is exactly the error? Commented Mar 31, 2021 at 20:10
  • It works but I want to export xml file to my directory but I don't know how Commented Mar 31, 2021 at 20:13

1 Answer 1

2
  1. Firstly, if xmlcontents is just correct xml file - you can just write it back to file as string :)

    with open('somefile.xml', 'w') as the_file:
        the_file.write(xmlcontents)
    
  2. Secondly, use ElementTree:

    from xml.etree.ElementTree import XML, fromstring, ElementTree
    myxml = fromstring(xmlcontents)
    ElementTree(myxml).write('output.xml')
    
Sign up to request clarification or add additional context in comments.

1 Comment

Note that generally, if the OP isn't making it clear what they're asking in their question, it's better to get the question clarified and not answer it until it is. See the Answer Well-Asked Questions section of How to Answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.