用ET find和findall進行xml數據配置_byseyOrd


前言

  ET支持部分的Xpath語法,對於測試是個非常好用的工具,ET是目前最好用的xml數據文件讀取的工具包

find和findall支持的xpath語法

標號 語法 說明
1 tag 查找所有具有指定名稱tag的子元素。例如:country表示所有名為country的元素,country/rank表示所有名為country的元素下名為rank的元素。
2 * 查找所有元素。如:*/rank表示所有名為rank的孫子元素。
3 . 選擇當前元素。在xpath表達式開頭使用,表示相對路徑。
4 // 選擇當前元素下所有級別的所有子元素。xpath不能以“//”開頭。
5 .. 選擇父元素。如果視圖達到起始元素的祖先,則返回None(或空列表)。起始元素為調用find(或findall)的元素。
6 [@attrib] 選擇具有指定屬性attrib的所有子元素。
7 [@attrib='value'] 選擇指定屬性attrib具有指定值value的元素,該值不能包含引號。
8 [tag] 選擇所有具有名為tag的子元素的元素。
9 [.='text'] Python3.7+,選擇元素(或其子元素)完整文本內容為指定的值text的元素。
10 [tag='text'] 選擇元素(或其子元素)名為tag,完整文本內容為指定的值text的元素。
11 [position] 選擇位於給定位置的所有元素,position可以是以1為起始的整數、表達式last()或相對於最后一個位置的位置(如:last()-1)

 

例子

import os
import xml.etree.cElementTree as ET
xml_string="""<?xml version="1.0"?>
<data>
  <country name="Liechtenstein">
    <rank updated="yes">2</rank>
    <year>2008</year>
    <gdppc>141100</gdppc>
    <neighbor name="Austria" direction="E"/>
    <neighbor name="Switzerland" direction="W"/>
  </country>
  <country name="Singapore">
    <rank updated="yes">5</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor name="Malaysia" direction="N"/>
  </country>
  <country name="Panama">
    <rank updated="yes">69</rank>
    <year>2011</year>
    <gdppc>2011</gdppc>
    <neighbor name="Costa Rica" direction="W"/>
    <neighbor name="Colombia" direction="E"/>
  </country>
    <country name="Washington">
    <rank updated="yes">55</rank>
    <gdppc>13600</gdppc>
  </country>
</data>
"""
root=ET.fromstring(xml_string)# ET有兩種引入xml的方式,fromstring(xml_string) 和 parse(filename)
#查找data下所有名為country的元素
for country in root.findall("country"):
    print("name:"+country.get("name"))# 元素.get("屬性名稱")得到屬性值
    #查找country下所有名為year的元素
    year=country.find("./year")
    if year:
        print("year:"+year.text)
#查找名為neighbor的孫子元素
for neighbor in root.findall("*/neighbor"):
    print("neighbor:"+neighbor.get("name"))
#查找country下的所有子元素
for ele in root.findall("country//"):
    print(ele.tag)
#查找當前元素的父元素,結果為空
print(root.findall(".."))
#查找與名為rank的孫子元素同級的名為gdppc的元素
for gdppc in root.findall("*/rank/../gdppc"):
    print("gdppc:"+gdppc.text)
#查找data下所有具有name屬性的子元素
for country in root.findall("*[@name]"):
    print(country.get("name"))
#查找neighbor下所有具有name屬性的子元素
for neighbor in root.findall("country/*[@name]"):
    print(neighbor.get("name"))
#查找country下name屬性值為Malaysia的子元素
print("direction:"+root.find("country/*[@name='Malaysia']").get("direction"))
#查找root下所有包含名為year的子元素的元素
for country in root.findall("*[year]"):
    print("name:"+country.get("name"))
#查找元素(或其子元素)文本內容為2011的元素(Python3.7+)
#print(len(root.findall("*[.='2011']")))
#查找元素(或其子元素)名為gdppc,文本內容為2011的元素
for ele in root.findall("*[gdppc='2011']"):
    print(ele.get("name"))
#查找第二個country元素
print(root.find("country[2]").get("name"))

 


免責聲明!

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



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