我正在解析具有“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/