【问题标题】:How to combine None and "g" namespace?如何结合 None 和“g”命名空间?
【发布时间】:2021-08-12 08:39:41
【问题描述】:

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

<feed ...
    <entry>
        <g:id>2</g:id>
        <title>Some product

在获取xpath时尝试使用namespaces属性:

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 示例?
  • 另外——lxml documentation 表示 XPath 不支持默认命名空间。因此,在对所链接问题的公认答案中采取的方法是必要的。
  • 我怀疑这些元素并不是真正在一个空的命名空间中。你能发布整个最外层的&lt;feed ...&gt; 元素吗?

标签: python xpath namespaces lxml


【解决方案1】:

要记住的重要一点是命名空间前缀只是一个任意前缀。它不需要为空,您可以随意设置。

从上下文来看,我假设这就是您的 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>]

【讨论】:

    猜你喜欢
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 2010-10-20
    • 2020-03-13
    相关资源
    最近更新 更多