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

2024-06-26 14:55:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从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>

我将lxml与python结合使用。你知道吗

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结果的属性。你知道吗


Tags: pathinreportcomtreefordatacode