gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:05:23 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com