0

我正在使用 python minidom 为 zabbix 生成一个 XML 模板

#!/usr/bin/env python

from xml.etree import ElementTree
from xml.dom import minidom
#from xml.etree.cElementTree import ElementTree
from xml.etree.ElementTree import Element, SubElement, Comment
import sys

def prettify(elem):
    """returns a xml in pretty format"""
    orig_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(orig_string)
    return reparsed.toprettyxml(indent="    ")

def createXml():
    zabbix_export = Element('zabbix_export',{'version':'1.0','date':'07/03/2012','time':'18:40'})
    #zabbix_export = Element('zabbix_export')
    comment = Comment('Generated in python')
    zabbix_export.append(comment)

    hosts = SubElement(zabbix_export,'hosts')

    host = SubElement(hosts, 'host', {'name':'Template_KSHK_Stats'})
    host.text = 'this child contains text'

    proxy_hostid = SubElement(host, 'proxy_hostid')
    proxy_hostid.text = 'this is the subchild'

    useip = SubElement(host, 'useip')
    useip.text = '0'

    ip = SubElement(host, 'ip')
    ip.text = '0.0.0.0'

    port = SubElement(host, 'port')
    port.text = '0'

    print prettify(zabbix_export)

def main():
    createXml()

if __name__ == "__main__":
    main()

这是我得到的输出:

<?xml version="1.0" ?>
<zabbix_export date="07/03/2012" time="18:40" version="1.0">
    <!-- Generated in python -->
    <hosts>
        <host name="Template_KSHK_Stats">
            this child contains text
            <proxy_hostid>
                this is the subchild
            </proxy_hostid>
            <useip>
                0
            </useip>
            <ip>
                0.0.0.0
            </ip>
            <port>
                0
            </port>
            <status>
                3
            </status>

我希望宿主树中的子元素采用这种格式,

proxy_hostid>this is the subchild</proxy_hostid>
<useip>0</useip>
<ip>0.0.0.0</ip>
<port>0</port>
<status>3</status>

但由于来自http://www.doughellmann.com/PyMOTW/xml/etree/ElementTree/create.html的 prettifyhack

zabbix 没有正确读取子元素..

知道如何解决这个问题吗?

固定的:

使用

def prettify(elem):
    """returns a xml in pretty format"""
    orig_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(orig_string)
    uglyXml = reparsed.toprettyxml(indent="  ")
    text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL)
    prettyXml = text_re.sub('>\g<1></', uglyXml)
    return prettyXml
4

1 回答 1

0

不要美化它。正如 Dougs 页面上所提到的,它不会使人眼更容易(如果您需要调试 XML,这很有帮助),但在某些情况下这会改变内容。你的就是这些案例之一。

于 2012-03-08T10:31:57.957 回答