有没有办法从ElementTree元素获取行号 [英] Is there a way to get a line number from an ElementTree Element

查看:162
本文介绍了有没有办法从ElementTree元素获取行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我使用Python 3.2.1的cElementTree解析了一些XML文件,在解析过程中,我注意到某些标记缺少属性信息。我想知道是否有任何简单的方法来获取xml文件中这些元素的行号。

So I'm parsing some XML files using Python 3.2.1's cElementTree, and during the parsing I noticed that some of the tags were missing attribute information. I was wondering if there is any easy way of getting the line numbers of those Elements in the xml file.

推荐答案

文档,我看不到使用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.

这篇关于有没有办法从ElementTree元素获取行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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