【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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM