You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从XMLschema的错误迭代器中获取错误行号?

获取xmlschema验证错误对应的XML行号

要解决这个问题,核心是利用lxml解析器保留的XML节点位置信息——标准库的xml.etree.ElementTree不会记录行号,而lxml会为解析后的元素添加sourceline属性。

步骤1:安装lxml

如果还没安装,先执行:

pip install lxml

步骤2:修改验证代码

调整你的函数,让schema用lxml解析XML,并从错误对象中提取行号:

def get_validation_errors(xml_file, xsd_file):
    schema = xmlschema.XMLSchema(xsd_file)
    # 用lxml解析XML,保留节点位置信息
    xml_tree = schema.parse(xml_file, parser='lxml')
    validation_error_iterator = schema.iter_errors(xml_tree)
    
    errors = list()
    for idx, validation_error in enumerate(validation_error_iterator, start=1):
        line_num = None
        instance = validation_error.instance
        
        # 优先从错误关联的节点取行号
        if hasattr(instance, 'sourceline'):
            line_num = instance.sourceline
        # 处理文本节点的情况(比如枚举值错误属于文本内容)
        elif hasattr(instance, 'getparent'):
            parent_node = instance.getparent()
            if hasattr(parent_node, 'sourceline'):
                line_num = parent_node.sourceline
        
        err_entry = f'[{idx}] path: {validation_error.path} | line: {line_num} | reason: {validation_error.reason} | message: {validation_error.message}'
        errors.append(err_entry)
        print(err_entry)
    
    return errors

说明

  • 用schema.parse(xml_file, parser='lxml')替代直接传入文件名给iter_errors,确保解析后的XML节点携带行号信息。
  • 错误对象的instance属性对应触发验证失败的XML节点(或文本内容):
    • 如果是元素节点,直接取sourceline;
    • 如果是文本节点(比如你示例中的枚举值错误),则取其父元素的行号,对应XML中该元素所在的行。

运行修改后的代码,你会得到类似这样的输出:

[1] path: /KnudeGroup/Knude[5]/StatusKode | line: 23 | reason: value must be one of [1, 2, 3, 4, 8] | message: failed validating 0 with XsdEnumerationFacets([1, 2, 3, 4, 8])

内容的提问来源于stack exchange,提问作者Frederikke Kappelhøj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 16:52:36