使用嵌套标记中的文本提取父标记属性

时间:2016-01-29 15:22:47

标签: python xml lxml

我正在尝试从XML中返回信息,其中找到了特定的文本字符串。

示例:

<xml xmlns:condition="uri:founder.com/data/condition/2.0" xmlns:report="uri:founder.com/data/report/2.0"> 
  <condition:locate name="VAR1">
    <condition:path value="/foo/bar/*'>
            <report:code>12345</report:code>
    </condition:path>
  </condition:locate>
  <condition:locate name="VAR2">
    <condition:path value="/spam/eggs/*">
            <report:code>567891</report:code>
    </condition:path>
  </condition:locate>

我正在使用带Python的lxml。

from lxml import etree
tree = etree.parse('test.xml')
root = tree.getroot()
codes = []
namespaces = {'condition':'uri:founder.com/data/condition/2.0','report':'uri:founder.com/data/report/2.0'}
for items in iter(root.xpath('//condition:*/report:code/text()',namespaces=namespaces)):
        codes.append(items)
sett=set(codes)
print(sett)

我正在使用set()删除重复项。我可以成功检索代码值(12345和567891),但我需要带有条件名称和属性的父标签。

我一直在玩以下内容,但我只需要标记和属性的最终路径:

for i in sett:
    for x in root.xpath('//text()[contains(., {})]/parent::*'.format(i)):
        out = tree.getpath(x)
        print out,"\n\n\n"  

更新:现在我只需要获取xpath结果的属性。

0 个答案:

没有答案
相关问题