XML Declaration standalone ="yes"lxml

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)

  • @falsetru - 我的意思是,OP 选择另一个正确答案是不行的。您的更正确,因为它不会用硬编码值覆盖输入值。[这一点你知道——我只是在和其他人交谈。]另一个答案更容易实现,只是因为它在一行上需要更少的击键,并且只是懒惰的编程更容易在某些时候导致问题。 (2认同)