Clif Swiggett, 16.11.2009 01:03:
I've had two mysteries come up recently using etree.parse() (lxml version 2.2.2). Can anyone shed some light on how to work around these?
Start with this input ======input.html========= <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <h2 class="speechTitle"> <p>Foo</p> </h2> </body> </html> ======================
Note that this is an XML document.
... then parse using ...
htmlTree = etree.parse(open("input.html"), parser=etree.HTMLParser()) open("out.xml", "wb").write(etree.tostring(htmlTree))
You should really try to write less verbose code: htmlTree = etree.parse("input.html", parser=etree.HTMLParser()) htmlTree.write("out.xml") This is shorter and also a lot faster.
... the resulting XML is corrupted in two ways:
That's because you are parsing it with an HTML parser. For parsing XML, use an XML parser. Stefan