Python解析xml文件,此实例将xml设置为模版(from lxml import etree)

xml文件(template.xml)


    
    
        
        
            
                "Mouser Factory"
            
            
                "Technodrome"
            
            
                "Siemens, SIMATIC, S7-200"
            
            
                conpot.emulators.misc.uptime.Uptime
            
            
                "0.0"
            
            
                "Siemens AG"
            
            
                "CP 443-1 EX40"
            
            
                "Venus"
            
            
                "72"
            
            
                [random.randint(0,1) for b in range(0,128)]
            
            
                [random.randint(0,1) for b in range(0,32)]
            
            
                [random.randint(0,1) for b in range(0,128)]
            
            
                [random.randint(0,1) for b in range(0,32)]
            
            
                [random.randint(0,1) for b in range(0,128)]
            
            
                [random.randint(0,1) for b in range(0,32)]
            
            
                [random.randint(0,1) for b in range(0,8)]
            
            
                [0 for b in range(0,32)]
            
            
                "Original Siemens Equipment"
            
            
                "88111222"
            
            
                "IM151-8 PN/DP CPU"
            
            
                ""
            
        
    

解析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 details
                    for entity in template_details:

                        if entity.attrib['name'] == 'unit':
                            template_unit = entity.text

                        elif entity.attrib['name'] == 'vendor':
                            template_vendor = entity.text

                        elif entity.attrib['name'] == 'description':
                            template_description = entity.text

                        elif entity.attrib['name'] == 'protocols':
                            template_protocols = entity.text

                        elif entity.attrib['name'] == 'creator':
                            template_creator = entity.text

                    print("   --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 IEC104
       Unit:        Siemens - S7-300
       Desc:        Creates a simple device for IEC 60870-5-104
       Protocols:   IEC104, SNMP
       Created by:  Patrick Reichenberger

   --template default
       Unit:        Siemens - S7-200
       Desc:        Rough simulation of a basic Siemens S7-200 CPU with 2 slaves
       Protocols:   HTTP, MODBUS, s7comm, SNMP
       Created by:  the conpot team

   --template proxy
       Unit:        None - Proxy
       Desc:        Sample template that demonstrates the proxy feature.
       Protocols:   Proxy
       Created by:  the conpot team

   --template guardian_ast
       Unit:        Guardian - Guardian AST tank-monitoring system
       Desc:        Guardian AST tank-monitoring system
       Protocols:   guardian_ast
       Created by:  the conpot team

   --template ipmi
       Unit:        IPMI - 371
       Desc:        Creates a simple IPMI device
       Protocols:   IPMI
       Created by:  Lukas Rist

   --template kamstrup_382
       Unit:        Kamstrup - 382
       Desc:        Register clone of an existing Kamstrup 382 smart meter
       Protocols:   Kamstrup
       Created by:  Johnny Vestergaard

解析core.databus

import random
from lxml import etree



def set_value(self, key, value):
        logger.debug('DataBus: Storing key: [%s] value: [%s]', key, value)
        self._data[key] = value
        # notify observers
        if key in self._observer_map:
            gevent.spawn(self.notify_observers, key)


def initialize(self, config_file):
        self.reset()
        assert self.initialized.isSet() is False
        logger.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._data
            print ('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 list
                    params = 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)