【发布时间】:2012-11-07 16:11:10
【问题描述】:
我有一个要解析的 XML,这对我来说真的很棘手。
<bundles>
<bundle>
<bitstreams>
<bitstream>
<id>1234</id>
</bitstream>
</bitstream>
<name>FOO</name>
</bundle>
<bundle> ... </bundle>
</bundles>
我想遍历这个 XML 并找到 bitstreams 内的所有 id 值,用于 bundle,其中 name 元素的值为'FOO'。我对任何未命名为“FOO”的捆绑包不感兴趣,捆绑包中可能有任意数量的捆绑包和任意数量的比特流。
我一直在使用 tree.findall('./bundle/name') 来查找 FOO 包,但这只是返回一个列表,我无法为 id 值单步执行:
for node in tree.findall('./bundle/name'):
if node.text == 'FOO':
id_values = tree.findall('./bundle/bitstreams/bitstream/id')
for value in id_values:
print value.text
这会打印出 所有 id 值,而不是包“FOO”的值。
我如何遍历这棵树,找到 name FOO 的 bundle,获取这个 bundle 节点并收集 id 值嵌套在里面吗?这里的 XPath 参数不正确吗?
我在 Python 中工作,使用 lxml 绑定 - 但我相信任何 XML 解析器都可以;这些不是大型 XML 树。
【问题讨论】:
-
你能告诉我们你到目前为止的代码吗?
标签: python xml-parsing lxml siblings dspace