简体   繁体   中英

Pretty formatting xml file in Python using lxml

I am trying to add a vhost entry to tomcat server.xml using python lxml

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')

The problem is that it is removing the <?xml version='1.0' encoding='utf-8'?>

line on top of the file from the output and the vhost entry is all in one line .How can I add the xml element in a pretty way like

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

First you need to parse existing file with remove_blank_text so that it's clean and with no extra spaces that I think is a problem in this case

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

Then you're safe to write it back to disk with pretty_print and xml_declaration set in doc.write()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM