且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有办法从ElementTree元素获取行号

更新时间:2022-06-12 23:56:49

文档,我看不到使用cElementTree做到这一点。

Looking at the docs, I see no way to do this with cElementTree.

但是我对 XML实现的lxml 版本。
应该使用libxml2替换掉了。元素具有 sourceline 属性。 (以及获得许多其他XML功能。)

However I've had luck with lxmls version of the XML implementation. Its supposed to be almost a drop in replacement, using libxml2. And elements have a sourceline attribute. (As well as getting a lot of other XML features).

仅需说明的是,我仅在python 2.x中使用了它-不知道它如何/是否在3下工作。 x-但可能值得一看。

Only caveat is that I've only used it in python 2.x - not sure how/if it works under 3.x - but might be worth a look.

附录:
从他们的首页开始,他们说:

Addendum: from their front page they say :


lxml XML工具箱是C库libxml2
和libxslt的Pythonic绑定。它的独特之处在于,它结合了这些库的速度和XML
功能的完整性以及
本机Python API的简单性,该API主要兼容但优于著名的
ElementTree API。最新版本适用于从2.3到3.2的所有CPython版本
。有关
的背景和lxml项目的目标的更多信息,请参见介绍。一些常见的问题是
在常见问题解答中回答的。

The lxml XML toolkit is a Pythonic binding for the C libraries libxml2 and libxslt. It is unique in that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible but superior to the well-known ElementTree API. The latest release works with all CPython versions from 2.3 to 3.2. See the introduction for more information about background and goals of the lxml project. Some common questions are answered in the FAQ.

所以看起来python 3.x没问题。

So it looks like python 3.x is OK.