删除 lxml 中的所有命名空间?
我正在使用 google 的一些数据 API,使用 python 中的 lxml 库。命名空间在这里是一个很大的麻烦。对于我正在做的很多工作(主要是 xpath 的东西),最好直接忽略它们。
有没有一种简单的方法可以忽略 python/lxml 中的 xml 命名空间?
谢谢!
I'm working with some of google's data APIs, using the lxml library in python. Namespaces are a huge hassle here. For a lot of the work I'm doing (xpath stuff, mainly), it would be nice to just plain ignore them.
Is there a simple way to ignore xml namespaces in python/lxml?
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想从元素和属性中删除所有名称空间,我建议使用下面所示的代码。
上下文:在我的应用程序中,我获取 SOAP 响应流的 XML 表示形式,但我对在客户端构建对象不感兴趣;我只对 XML 表示本身感兴趣。此外,我对任何名称空间事物都不感兴趣,这只会使事情变得比我的目的所需的更加复杂。因此,我只需从元素中删除名称空间,并删除包含名称空间的所有属性。
打印:
If you'd like to remove all namespaces from elements and attributes, I suggest the code shown below.
Context: In my application I'm obtaining XML representations of SOAP response streams, but I'm not interested on building objects on the client side; I'm only interested on XML representations themselves. Moreover, I'm not interested on any namespace thing, which only makes things more complicated than they need to be, for my purposes. So, I simply remove namespaces from elements and I drop all attributes which contain namespaces.
which prints:
在 lxml 中,如果存在命名空间,则
some_element.tag
是一个类似{namespace-uri}local-name
的字符串,否则只是local-name
。请注意,它是非元素节点上的非字符串值(例如注释)。试试这个:
在 Python 2.x 上,标签可以是 ASCII 字节字符串或 Unicode 字符串。 startswith 方法的存在可以测试其中任何一个。
In lxml
some_element.tag
is a string like{namespace-uri}local-name
if there is a namespace, justlocal-name
otherwise. Beware that it is a non string value on non-element nodes (such as comments).Try this:
On Python 2.x the tag can be either an ASCII byte-string or an Unicode string. The existence of a startswith method tests for either.