我正在解析一个xml,进行一些更改并保存到一个新文件中。它有我想保留的声明<?xml version="1.0" encoding="utf-8" standalone="yes"?>。当我保存我的新文件时,我正在释放standalone="yes"位。我怎么才能把它藏在里面?这是我的代码:
templateXml = """<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<package>
<provider>Some Data</provider>
<studio_display_name>Some Other Data</studio_display_name>
</package>"""
from lxml import etree
tree = etree.fromstring(templateXml)
xmlFileOut = '/Users/User1/Desktop/Python/Done.xml'
with open(xmlFileOut, "w") as f:
f.write(etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8'))发布于 2013-08-11 16:24:14
您可以将standalone关键字参数传递给tostring()
etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone=True)发布于 2013-08-11 16:24:45
使用standalone指定tree.docinfo.standalone。
尝试以下几个方面:
from lxml import etree
tree = etree.fromstring(templateXml).getroottree() # NOTE: .getroottree()
xmlFileOut = '/Users/User1/Desktop/Python/Done.xml'
with open(xmlFileOut, "w") as f:
f.write(etree.tostring(tree, pretty_print=True, xml_declaration=True,
encoding=tree.docinfo.encoding,
standalone=tree.docinfo.standalone))发布于 2015-05-07 15:49:51
如果要在XML中显示standalone='no'参数,则必须将其设置为False,而不是“no”。就像这样:
etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone=False)如果没有,则默认情况下独立设置为“是”。
https://stackoverflow.com/questions/18173983
复制相似问题