在python中格式化xml文件

时间:2014-11-13 04:38:48

标签: python xml

我正在尝试使用python lxml

将一个vhost条目添加到tomcat server.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>

感谢。

1 个答案:

答案 0 :(得分:1)

首先,您需要使用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)
相关问题