python - 如何结合 None 和 "g"命名空间?

标签 python xpath namespaces lxml

我正在解析具有“g”和空命名空间的 Google 产品 XML 文件。

<feed ...
    <entry>
        <g:id>2</g:id>
        <title>Some product
正在尝试使用 namespaces获取时的属性 xpath :
tree.xpath('/feed/entry/g:title',namespaces:{'': 'http://www.w3.org/2005/Atom', 'g': 'http://base.google.com/ns/1.0'})
返回
empty namespace prefix is not supported in XPath
如何使用空命名空间?

最佳答案

要记住的重要一点是命名空间前缀只是一个任意前缀。它不需要是空的,你可以让它成为你想要的任何东西。
从上下文来看,我假设这就是您的 XML 的样子?
如果是这样,则没有前缀的元素不在空命名空间中。他们在 http://www.w3.org/2005/Atom命名空间,您只需在函数调用中为其分配一个任意前缀。

In [1]: from lxml import etree

In [2]: string = '''
   ...: <feed xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0">
   ...:     <entry>
   ...:         <g:id>2</g:id>
   ...:         <title>Some product</title>
   ...:     </entry>
   ...: </feed>
   ...: '''

In [3]: root = etree.fromstring(string)

In [4]: root.xpath('/foo:feed/foo:entry/foo:title',namespaces={'foo': 'http://www.w3.org/2005/Atom', 'bar': 'http:/
   ...: /base.google.com/ns/1.0'})
Out[4]: [<Element {http://www.w3.org/2005/Atom}title at 0x10a3d7d40>]

In [5]: root.xpath('/foo:feed/foo:entry/bar:id',namespaces={'foo': 'http://www.w3.org/2005/Atom', 'bar': 'http://b
    ...: ase.google.com/ns/1.0'})
Out[5]: [<Element {http://base.google.com/ns/1.0}id at 0x10a9ed4c0>]

关于python - 如何结合 None 和 "g"命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67665328/

相关文章:

xpath - 选择所有节点,直到特定的给定节点/标签

ios - Appium 从元素获取 xpath?

c++ - 使用命名空间标准和模板类

c++ - 使用 C+ +'s namespace{} sort-of like C#' s #region/#endregion

python - 如何在 PyTorch 中正确实现数值数据的一维 CNN?

python - 计算字符串中的连续数字

python - 尝试导入 Tensorflow 时出现 ModuleNotFoundError

python - 该标签已存在于 HTML 代码中,但无法通过 xpath 到达

module - F# 命名空间和模块 : Awesome collections from Wikibooks

python - 如何在 Django 中过滤 DateTimeField 的日期?