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