假设有如下xml在/home/abc.xml位置
<A>
<B id="" name="apple"/>
<B id="" name="orange"/>
<B id="" 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)