[英]How do I parse and write XML using Python's ElementTree without moving namespaces around?
[英]Python/ElementTree: Write to file without namespaces
我正在尝试将 ElementTree 对象写入磁盘。 一切正常,除了输出文件如下所示:
<html:html lang="en-US" xml:lang="en-US" xmlns:html="http://www.w3.org/1999/xhtml">
<html:head>
<html:title>vocab</html:title>
<html:style type="text/css"> ...
由于它有html:
命名空间信息,浏览器无法呈现它。
如何让 etree 在没有html:
命名空间信息的情况下将一些 html 保存到磁盘?
这是我用来编写的代码:
with open('/path/to/file.html', mode='w', encoding='utf-8') as outfile:
mypage.write(outfile)
谢谢!
我一直在使用这个解决方法:
from xml.etree import ElementTree as ET
ET.register_namespace('', 'http://www.w3.org/1999/xhtml')
然后html:
前缀将在输出时替换为空格。
嗯,我已经让它工作了,但是有一种迂回的方法。
我正在获取树的字符串(使用etree.tostrng()
),然后使用re.sub('html:', '', thetext)
删除命名空间信息。 然后,我只是将字符串正常写入磁盘。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.