spe*_*zor 11 python xml parsing lxml xml-parsing
我有一个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'))
Run Code Online (Sandbox Code Playgroud)
ale*_*cxe 17
您可以将standalone关键字参数传递给tostring():
etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone="yes")
Run Code Online (Sandbox Code Playgroud)
fal*_*tru 10
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))
Run Code Online (Sandbox Code Playgroud)