# adds declaration with version and encoding regardless of
# which attributes were present in the original declaration
# expects utf-8 encoding (encode/decode calls)
# depending on your needs you might want to improve that
from lxml import etree
from xml.dom.minidom import parseString
xml1 = '''\
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root SYSTEM "example.dtd">
<root>...</root>
'''
xml2 = '''\
<root>...</root>
'''
def has_xml_declaration(xml):
return parseString(xml).version
def process(xml):
t = etree.fromstring(xml.encode()).getroottree()
if has_xml_declaration(xml):
print(etree.tostring(t, xml_declaration=True, encoding=t.docinfo.encoding).decode())
else:
print(etree.tostring(t).decode())
process(xml1)
process(xml2)
以下将包括DOCTYPE和XML声明:
from lxml import etree
from StringIO import StringIO
tree = etree.parse(StringIO('''<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "eggs"> ]>
<root>
<a>&tasty;</a>
</root>
'''))
docinfo = tree.docinfo
print etree.tostring(tree, xml_declaration=True, encoding=docinfo.encoding)
import sys
from StringIO import StringIO
from lxml import etree
xml = r'''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>example</title>
</head>
<body>
<p>This is an example</p>
</body>
</html>'''
tree = etree.fromstring(xml).getroottree() # or etree.parse(file)
tree.write(sys.stdout, xml_declaration=True, encoding=tree.docinfo.encoding)
输出
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>example</title>
</head>
<body>
<p>This is an example</p>
</body>
</html>
tl;dr
以下将包括DOCTYPE和XML声明:
注意,
tostring
不会保留DOCTYPE
如果您创建了Element
(例如,使用fromstring
),它只在您使用parse
处理XML时起作用。更新:正如J.F. Sebastian所指出的,我关于
fromstring
的断言是不正确的。下面是一些代码来突出
Element
和ElementTree
序列化之间的区别:结果是:
您还可以使用
fromstring()
保留DOCTYPE和XML声明:输出
注意xml声明(使用正确的编码)和doctype都存在。它甚至(可能不正确)在xml声明中使用
'
,而不是"
,并将Content-Type
添加到<head>
。对于@John Keyes' example input它产生的结果与答案中的
etree.tostring()
相同。相关问题 更多 >
编程相关推荐