首页 > 解决方案 > 寻找有关构建从通用文件解析器派生的 XML 解析器的技巧

问题描述

我需要在 python 中为 XML 文件实现一个解析器类,并且我需要将其设为来自以下(不完整)类的派生类。

class AbstractLogsParser(object):
    # Different test statuses
    TEST_RES_PASS = 0
    TEST_RES_FAIL = 1
    TEST_RES_SKIP = 2
    def __init__(self, logs_extension):
        """
        Base class constructor.
        @param    logs_extension  Extension of log files to parse.
        """
        self._logs_ext = '.'+logs_extension
    def get_result_by_type(self, result_type): 
        """
        Returns number of passed, failed or skipped tests.
        @param    result_type          Type of results to return.
        """
        return -1
    def generate_detailed_report(self):
        """
        Generates detailed report on each test suite.
        """
        raise Exception("generate_detailed_report is not implemented")
    def process_logs(self, folder):
        """
        Parses all log files with target extension in the specified folder. @param folder Folder to look up for log files.
        """
        raise Exception("process_logs is not implemented")

派生的 XML 解析器将具有用于不同度量和统计的方法,但似乎实际的解析需要在基类中进行。最初我想使用ElementTree来执行此操作,但是我看不到如何对基类中的方法进行编码以适应我需要构建的继承的 XML 解析器类。

AbstractLogsParser 构造函数将文件扩展名作为参数,因此该process_logs方法需要能够解析不同格式的文件。假设日志文件中的关键字始终相同,使用正则表达式逐行解析日志文件是否明智?我只是在寻找一些关于如何做好实施的技巧。

这是解析器应处理的 XML 日志文件的示例。

<test_results test_suite="GAP_CONN_001"> 
    <environment>LOCAL</environment> 
    <debug>Test suite start</debug>
    <tc_result id="conn_bv_001" result="PASS">
        <debug>Run 2 sequences</debug> 
    </tc_result>
    <tc_result id="conn_bv_002" result="FAIL" /> 
    <tc_result id="conn_bv_002" result="PASS" /> 
    <tc_result id="conn_bv_004" result="SKIP">
        <reason>No pass criteria</reason>
    </tc_result>
</test_results>

标签: pythonregexxmlparsing

解决方案


推荐阅读