Parsing an xml file and creating another from the parsed object

Question:

I am trying to parse an xml file(containing bad characters) using lxml module in recover = True mode.
Below is the code snippet

from lxml import etree
f=open('test.xml')
data=f.read()
f.close()
parser = etree.XMLParser(recover=True)
x = etree.fromstring(data, parser=parser)

Now I want to create another xml file (test1.xml) from the above object (x)
Could anyone please help in this matter.

Thanks

Answers:

I think this is what you are searching for

from lxml import etree

# opening the source file
with open('test.xml','r') as f:
    # reading the number
    data=f.read()
   
parser = etree.XMLParser(recover=True)
# fromstring() parses XML from a string directly into an Element
x = etree.fromstring(data, parser=parser)

# taking the content retrieved
y = etree.tostring(x, pretty_print=True).decode("utf-8")

# writing the content on the output file
with open('test1.xml','w') as f:
    f.write(y)
Answered By: Antonino
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.