Python解析xml文件,此实例将xml设置为模版(from lxml import etree)
生活随笔
收集整理的這篇文章主要介紹了
Python解析xml文件,此实例将xml设置为模版(from lxml import etree)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
xml文件(template.xml)
<core><template><!-- General information about the template --><entity name="unit">S7-200</entity><entity name="vendor">Siemens</entity><entity name="description">Rough simulation of a basic Siemens S7-200 CPU with 2 slaves</entity><entity name="protocols">HTTP, MODBUS, s7comm, SNMP</entity><entity name="creator">the conpot team</entity></template><databus><!-- Core value that can be retrieved from the databus by key --><key_value_mappings><key name="FacilityName"><value type="value">"Mouser Factory"</value></key><key name="SystemName"><value type="value">"Technodrome"</value></key><key name="SystemDescription"><value type="value">"Siemens, SIMATIC, S7-200"</value></key><key name="Uptime"><value type="function">conpot.emulators.misc.uptime.Uptime</value></key><key name="sysObjectID"><value type="value">"0.0"</value></key><key name="sysContact"><value type="value">"Siemens AG"</value></key><key name="sysName"><value type="value">"CP 443-1 EX40"</value></key><key name="sysLocation"><value type="value">"Venus"</value></key><key name="sysServices"><value type="value">"72"</value></key><key name="memoryModbusSlave0BlockA"><value type="value">[random.randint(0,1) for b in range(0,128)]</value></key><key name="memoryModbusSlave0BlockB"><value type="value">[random.randint(0,1) for b in range(0,32)]</value></key><key name="memoryModbusSlave255BlockA"><value type="value">[random.randint(0,1) for b in range(0,128)]</value></key><key name="memoryModbusSlave255BlockB"><value type="value">[random.randint(0,1) for b in range(0,32)]</value></key><key name="memoryModbusSlave1BlockA"><value type="value">[random.randint(0,1) for b in range(0,128)]</value></key><key name="memoryModbusSlave1BlockB"><value type="value">[random.randint(0,1) for b in range(0,32)]</value></key><key name="memoryModbusSlave2BlockC"><value type="value">[random.randint(0,1) for b in range(0,8)]</value></key><key name="memoryModbusSlave2BlockD"><value type="value">[0 for b in range(0,32)]</value></key><key name="Copyright"><value type="value">"Original Siemens Equipment"</value></key><key name="s7_id"><value type="value">"88111222"</value></key><key name="s7_module_type"><value type="value">"IM151-8 PN/DP CPU"</value></key><key name="empty"><value type="value">""</value></key></key_value_mappings></databus> </core>解析core.template
template_xml = os.path.join(package_directory, 'templates', folder, 'template.xml')if os.path.isfile(template_xml):template_unit = template_vendor = template_description = template_protocols = template_creator = 'N/A'dom_template = etree.parse(template_xml)template_details = dom_template.xpath('//core/template/*')if template_details:# retrieve all template detailsfor entity in template_details:if entity.attrib['name'] == 'unit':template_unit = entity.textelif entity.attrib['name'] == 'vendor':template_vendor = entity.textelif entity.attrib['name'] == 'description':template_description = entity.textelif entity.attrib['name'] == 'protocols':template_protocols = entity.textelif entity.attrib['name'] == 'creator':template_creator = entity.textprint(" --template {0}".format(folder))print(" Unit: {0} - {1}".format(template_vendor, template_unit))print(" Desc: {0}".format(template_description))print(" Protocols: {0}".format(template_protocols))print(" Created by: {0}\n".format(template_creator))結果
--------------------------------------------------Available templates: ----------------------------------------------------template IEC104Unit: Siemens - S7-300Desc: Creates a simple device for IEC 60870-5-104Protocols: IEC104, SNMPCreated by: Patrick Reichenberger--template defaultUnit: Siemens - S7-200Desc: Rough simulation of a basic Siemens S7-200 CPU with 2 slavesProtocols: HTTP, MODBUS, s7comm, SNMPCreated by: the conpot team--template proxyUnit: None - ProxyDesc: Sample template that demonstrates the proxy feature.Protocols: ProxyCreated by: the conpot team--template guardian_astUnit: Guardian - Guardian AST tank-monitoring systemDesc: Guardian AST tank-monitoring systemProtocols: guardian_astCreated by: the conpot team--template ipmiUnit: IPMI - 371Desc: Creates a simple IPMI deviceProtocols: IPMICreated by: Lukas Rist--template kamstrup_382Unit: Kamstrup - 382Desc: Register clone of an existing Kamstrup 382 smart meterProtocols: KamstrupCreated by: Johnny Vestergaard解析core.databus
import random from lxml import etreedef set_value(self, key, value):logger.debug('DataBus: Storing key: [%s] value: [%s]', key, value)self._data[key] = value# notify observersif key in self._observer_map:gevent.spawn(self.notify_observers, key)def initialize(self, config_file):self.reset()assert self.initialized.isSet() is Falselogger.debug('Initializing databus using %s.', config_file)dom = etree.parse(config_file)entries = dom.xpath('//core/databus/key_value_mappings/*')for entry in entries:key = entry.attrib['name']value = entry.xpath('./value/text()')[0].strip()value_type = str(entry.xpath('./value/@type')[0])assert key not in self._dataprint ('Initializing key:%s value:%s as a value_type:%s.', key, value, value_type)logging.debug('Initializing %s with %s as a %s.', key, value, value_type)if value_type == 'value':self.set_value(key, eval(value))elif value_type == 'function':namespace, _classname = value.rsplit('.', 1)params = entry.xpath('./value/@param')module = __import__(namespace, fromlist=[_classname])_class = getattr(module, _classname)if len(params) > 0:# eval param to listparams = eval(params[0])self.set_value(key, _class(*(tuple(params))))else:self.set_value(key, _class())else:raise Exception('Unknown value type: {0}'.format(value_type))self.initialized.set()結果
Initializing key:%s value:%s as a value_type:%s. FacilityName "Mouser Factory" value Initializing key:%s value:%s as a value_type:%s. SystemName "Technodrome" value Initializing key:%s value:%s as a value_type:%s. SystemDescription "Siemens, SIMATIC, S7-200" value Initializing key:%s value:%s as a value_type:%s. Uptime conpot.emulators.misc.uptime.Uptime function Initializing key:%s value:%s as a value_type:%s. sysObjectID "0.0" value Initializing key:%s value:%s as a value_type:%s. sysContact "Siemens AG" value Initializing key:%s value:%s as a value_type:%s. sysName "CP 443-1 EX40" value Initializing key:%s value:%s as a value_type:%s. sysLocation "Venus" value Initializing key:%s value:%s as a value_type:%s. sysServices "72" value Initializing key:%s value:%s as a value_type:%s. memoryModbusSlave0BlockA [random.randint(0,1) for b in range(0,128)] value Initializing key:%s value:%s as a value_type:%s. memoryModbusSlave0BlockB [random.randint(0,1) for b in range(0,32)] value Initializing key:%s value:%s as a value_type:%s. memoryModbusSlave255BlockA [random.randint(0,1) for b in range(0,128)] value Initializing key:%s value:%s as a value_type:%s. memoryModbusSlave255BlockB [random.randint(0,1) for b in range(0,32)] value Initializing key:%s value:%s as a value_type:%s. memoryModbusSlave1BlockA [random.randint(0,1) for b in range(0,128)] value Initializing key:%s value:%s as a value_type:%s. memoryModbusSlave1BlockB [random.randint(0,1) for b in range(0,32)] value Initializing key:%s value:%s as a value_type:%s. memoryModbusSlave2BlockC [random.randint(0,1) for b in range(0,8)] value Initializing key:%s value:%s as a value_type:%s. memoryModbusSlave2BlockD [0 for b in range(0,32)] value Initializing key:%s value:%s as a value_type:%s. Copyright "Original Siemens Equipment" value Initializing key:%s value:%s as a value_type:%s. s7_id "88111222" value Initializing key:%s value:%s as a value_type:%s. s7_module_type "IM151-8 PN/DP CPU" value Initializing key:%s value:%s as a value_type:%s. empty "" value?
總結
以上是生活随笔為你收集整理的Python解析xml文件,此实例将xml设置为模版(from lxml import etree)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: golang:Linux下安装go环境
- 下一篇: Python3提示 No module