16

我有一个正在解析的 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'))
4

5 回答 5

23

您可以将standalone关键字参数传递给tostring()

etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone=True)
于 2013-08-11T16:24:14.497 回答
11

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))
于 2013-08-11T16:24:45.233 回答
3

如果要standalone='no'在 XML 标头中显示参数,则必须将其设置False为“no”而不是“no”。像这样:

etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone=False)

如果没有,standalone 将默认设置为“yes”。

于 2015-05-07T15:49:51.113 回答
0

如果您想完全禁用输出standaloneNone而不是Trueor False。听起来合乎逻辑,但需要一些时间才能真正找到并测试它。

etree.tostring(tree, xml_declaration = True, encoding='utf-8', standalone=None)

或使用上下文管理器和流etree.xmlfile序列化:

with etree.xmlfile(open('/tmp/test.xml'), encoding='utf-8') as xf:
    xf.write_declaration(standalone=None)
    with xf.element('html'):
        with xf.element('body'):
            element = etree.Element('p')
            element.text = 'This is paragraph'
            xf.write(element)
于 2018-03-07T14:02:40.180 回答
0
etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8')

如果您使用 lxml,将添加声明,但是我注意到他们的声明使用半引号而不是全引号。

您还可以通过将输出与您需要的静态字符串连接来获得所需的确切声明:

xml = etree.tostring(tree, pretty_print = True, encoding='UTF-8')
xml = '<?xml version=\"1.0\" encoding=\"utf-8\"?>\n' + xml
于 2017-03-21T23:03:07.117 回答