python3 lxml如何在前缀为空的情况下查找节点?
python3 lxml how to find node when prefix is empty?
.docx
文件中的 word/_rels/document.xml.rels
有一个空的前缀命名空间元素:<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
这导致我无法使用 findall
方法获取子节点。
简化示例:
>>> from lxml import etree
>>> etree.fromstring(b'<x><y id="1"/><y id="2"/></x>').findall('y')
[<Element y at 0x382d788>, <Element y at 0x382db48>]
>>> etree.fromstring(b'<x xmlns="wow"><y id="1"/><y id="2"/></x>').findall('y')
[]
# How to find these children nodes like previous one?
应该与 using the built-in xml.etree.ElementTree
相同,如果您使用 lxml
的 xpath()
方法,再加上另一个选项:
>>> from lxml import etree
>>> root = etree.fromstring(b'<x xmlns="wow"><y id="1"/><y id="2"/></x>')
>>> root.findall('{wow}y')
[<Element {wow}y at 0x2b489c8>, <Element {wow}y at 0x2b48588>]
>>> ns = {'d': 'wow'}
>>> root.findall('d:y', ns)
[<Element {wow}y at 0x2b489c8>, <Element {wow}y at 0x2b48588>]
>>> root.xpath('d:y', namespaces=ns)
[<Element {wow}y at 0x2b489c8>, <Element {wow}y at 0x2b48588>]
请注意,不带前缀的后代元素隐式继承了祖先的默认命名空间,这就是为什么在选择 <y>
时需要考虑命名空间,尽管命名空间是在父级声明的元素 <x>
.
.docx
文件中的 word/_rels/document.xml.rels
有一个空的前缀命名空间元素:<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
这导致我无法使用 findall
方法获取子节点。
简化示例:
>>> from lxml import etree
>>> etree.fromstring(b'<x><y id="1"/><y id="2"/></x>').findall('y')
[<Element y at 0x382d788>, <Element y at 0x382db48>]
>>> etree.fromstring(b'<x xmlns="wow"><y id="1"/><y id="2"/></x>').findall('y')
[]
# How to find these children nodes like previous one?
应该与 using the built-in xml.etree.ElementTree
相同,如果您使用 lxml
的 xpath()
方法,再加上另一个选项:
>>> from lxml import etree
>>> root = etree.fromstring(b'<x xmlns="wow"><y id="1"/><y id="2"/></x>')
>>> root.findall('{wow}y')
[<Element {wow}y at 0x2b489c8>, <Element {wow}y at 0x2b48588>]
>>> ns = {'d': 'wow'}
>>> root.findall('d:y', ns)
[<Element {wow}y at 0x2b489c8>, <Element {wow}y at 0x2b48588>]
>>> root.xpath('d:y', namespaces=ns)
[<Element {wow}y at 0x2b489c8>, <Element {wow}y at 0x2b48588>]
请注意,不带前缀的后代元素隐式继承了祖先的默认命名空间,这就是为什么在选择 <y>
时需要考虑命名空间,尽管命名空间是在父级声明的元素 <x>
.