【python】lxml查找属性为指定值的节点

假设有如下xml在/home/abc.xml位置

<A>
      <B  id="1" name="apple"/>
      <B  id="2" name="orange"/>
      <B  id="3" name="banana"/>
</A>

 

我们要查找其中id=1的节点B的名称,可以利用lxml中xpath来查找:

#!/usr/bin/python
#coding=utf-8

from lxml import etree

config_path = "/home/abc.xml"
def getIdName(id):
    content = ""
    with open(config_path, 'r') as f:
        content = f.read()
    xml = etree.fromstring(content)
    nodes = xml.xpath("//B[@id=%d]" % id)
    return nodes[0].get("name")
    
if __name__ == "__main__":
    getIdName(1)

 

posted @ 2016-07-27 11:23  匡子语  阅读(7697)  评论(0编辑  收藏  举报