word/_rels/document.xml.rels
在 .docx
文件有一个空的 preifx 命名空间元素:<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>
处声明的.
关于python3 lxml 当前缀为空时如何查找节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36280873/