如何从lxml错误中获取更多信息? [英] How to get more info from lxml errors?

查看:103
本文介绍了如何从lxml错误中获取更多信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我无法使用XSL IDE,因此我使用lxml编写了一个超简单的Python脚本,以使用给定的XSL转换来转换给定的XML文件,并将结果写入文件中.如下(删节):

Because I'm not able to use an XSL IDE, I've written a super-simple Python script using lxml to transform a given XML file with a given XSL transform, and write the results to a file. As follows (abridged):

p = XMLParser(huge_tree=True)
xml = etree.parse(xml_filename, parser=p)
xml_root = xml.getroot()
print(xml_root.tag)
xslt_root = etree.parse(xsl_filename)
transform = etree.XSLT(xslt_root)
newtext = transform(xml)
with open(output, 'w') as f:
    f.write(str(newtext))

我遇到以下错误:

"lxml.etree.XSLTApplyError:无法评估'select'表达式"

"lxml.etree.XSLTApplyError: Failed to evaluate the 'select' expression"

...但是我的XSLT中有很多select表达式.仔细查看并隔离了代码块之后,我仍然茫然不知哪个select失败了,或者为什么.

...but I have quite a number of select expressions in my XSLT. After having looked carefully and isolated blocks of code, I'm still at a loss as to which select is failing, or why.

无需尝试调试代码,是否可以从lxml中获取更多信息,例如行号或失败表达式中的引号?

推荐答案

aaaaa,当然,一旦我花时间发布问题,我就会偶然发现答案.

aaaaaand of course as soon as I actually take the time to post the question, I stumble upon the answer.

这可能是这个问题的副本,但我认为这还有Python方面的好处.

This might be a duplicate of this question, but I think the added benefit here is the Python side of things.

链接的答案指出,每个解析器都包含一个您可以访问的错误日志.唯一的技巧"就是捕获这些错误,以便您可以在日志创建后立即查看.

The linked answer points out that each parser includes an error log that you can access. The only "trick" is catching those errors so that you can look in the log once it's been created.

我这样做(也许也很差,但是行得通):

I did it thusly (perhaps also poorly, but it worked):

import os
import lxml.etree as etree
from lxml.etree import XMLParser
import sys

xml_filename = '(some path to an XML file)'
xsl_filename = '(some path to an XSL file)'
output = '(some path to a file)'

p = XMLParser(huge_tree=True)
xml = etree.parse(xml_filename, parser=p)
xml_root = xml.getroot()
xslt_root = etree.parse(xsl_filename)
transform = etree.XSLT(xslt_root)
newtext = None
try:
    newtext = transform(xml)
    with open(output, 'w') as f:
        f.write(str(newtext))
except:
    for error in transform.error_log:
        print(error.message, error.line)

此日志中的消息比打印到控制台的消息更具描述性,"line"元素将使您指向发生故障的行号.

The messages in this log are more descriptive than those printed to the console, and the "line" element will point you to the line number where the failure occurred.

这篇关于如何从lxml错误中获取更多信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆