python3 lxml 当前缀为空时如何查找节点?

标签 python xml lxml

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/

相关文章:

python - 使用 xpath() 使用 Python 和 lxml 查找祖父节点

python - 以 UTF-8 格式从 lxml 错误日志中打印消息

python - 有没有办法在 python doctest 中重新启动或重置 python 解释器?

python - python 中的组合 filter() 无法按预期工作

Python Noob - 愚蠢的问题?在 Python 解释器中工作,而不是在 CLI 中工作

html - 部分 SVG 蒙版不透明且颜色反转

java - 使用 XSL 修改现有 DOM

python - 在 python 中使用 lxml iterparse 解析大型 .bz2 文件 (40 GB)。未压缩文件不会出现的错误

python - 如何根据值确保 django 模型的唯一性?

javascript - 如何在 javascript 文件中使用自定义 xml 实体