How to create “virtual root” with Python's ElementTree?

拈花ヽ惹草 提交于 2020-01-03 15:11:31

问题


I am trying to use Python's ElementTree to generate an XHTML file.

However, the ElementTree.Element() just lets me create a single tag (e.g., HTML). I need to create some sort of a virtual root or whatever it is called so that I can put the various , DOCTYPES, etc.

How do I do that? Thanks


回答1:


I don't know if there's a better way but I've seen this done:

Create the base document as a string:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html></html>

Then parse that string to start your new document.




回答2:


I have/had the same problem. when i parse a document and write it back again the doctype defenition is not there anymore. but i found a solution browsing the documentation:

link text

Saving HTML Files #

To save a plain HTML file, just write out the tree.

tree.write("outfile.htm")

This works well, as long as the file doesn’t containg any embedded SCRIPT or STYLE tags.

If you want, you can add a DTD reference to the beginning of the file:

file = open("outfile.htm", "w")
file.write(DTD + "\n")
tree.write(file)
file.close()


来源:https://stackoverflow.com/questions/1070772/how-to-create-virtual-root-with-pythons-elementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!