【问题标题】:python generating xmlpython生成xml
【发布时间】:2012-03-08 09:42:39
【问题描述】:

我正在使用 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的美化黑客

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

【问题讨论】:

    标签: python linux zabbix


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      • 2014-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多