漂亮的格式化xml在Python中使用lxml的文件



我正在尝试使用 python lxml 向 tomcat 服务器添加一个 vhost 条目.xml

import io
from lxml import etree
newdoc = etree.fromstring('<Host name="getrailo.com" appBase="webapps"><Context path=""    docBase="/var/sites/getrailo.org" /><Alias>www.getrailo.org</Alias><Alias>my.getrailo.org</Alias></Host>')
doc = etree.parse('/root/server.xml')
root = doc.getroot()
for node1 in root.iter('Service'):
        for node2 in node1.iter('Engine'):
                node2.append(newdoc)
doc.write('/root/server.xml')

问题是它正在删除 <?xml version='1.0' encoding='utf-8'?>

输出中的文件顶部的行和 vhost 条目都在一行中。我怎样才能以一种漂亮的方式添加 xml 元素,例如

<Host name="getrailo.org" appBase="webapps">
         <Context path="" docBase="/var/sites/getrailo.org" />
         <Alias>www.getrailo.org</Alias>
         <Alias>my.getrailo.org</Alias>
</Host>
首先,

您需要使用remove_blank_text解析现有文件,使其干净且没有多余的空格,我认为在这种情况下是一个问题

parser = etree.XMLParser(remove_blank_text=True)
newdoc = etree.fromstring('/root/server.xml' parser=parser)

然后,您可以安全地将其写回磁盘,并pretty_printxml_declaration设置为doc.write()

doc.write('/root/server.xml',  
          xml_declaration=True, 
          encoding='utf-8', 
          pretty_print=True)

最新更新