python xml解析執行個體詳解,pythonxml解析執行個體

來源:互聯網
上載者:User

python xml解析執行個體詳解,pythonxml解析執行個體

python xml解析

first.xml 

<info> <person > <id>1</id> <name>fsy</name> <age >24</age> </person> <person> <id>2</id> <name>jianjian</name> <age>24</age> </person> <count id ='1'>1000</count> </info> 

from xml.etree import ElementTree as etree 

讀入

def read_xml(file): # parse()函數會返回一個能代表整篇文檔的對象。這不是根項目。要獲得根項目的引用可以調用getroot()方法。 tree = etree.parse(file) root = tree.getroot() return root 

得到資訊

def print_node(node): '''''列印結點基本資料''' print("node.tag:%s" % node.tag) print("node.attrib:%s"%node.attrib) print( "node.text:%s" % node.text) 

搜尋:

find_all >>> root = read_xml ('first.xml')   >>> res = root.findall("person") [<Element 'person' at 0x00000000033388B8>, <Element 'person' at 0x0000000003413D68>]  注意:findall只查詢直接的子節點 >>> r1 = root.findall("id") >>> r1 [] >>> r =tree.findall(".//id") >>> for e in r:   print( e,e.text)   <Element 'id' at 0x00000000034279F8> 1 <Element 'id' at 0x0000000003427B38> 2 

find:

#find()方法用來返回第一個匹配到的元素。當我們認為只會有一個匹配,或者有多個匹配但我們只關心第一個的時候,這個方法是很有用的。 >>> res[0].find("id") <Element 'id' at 0x0000000003413CC8> >>> print_node(res[0].find("id")) node.tag:id node.attrib:{} node.text:1 

find尋找失敗:

使用find要注意在布爾上下文中,如果ElementTree元素對象不包含子項目,其值則會被認為是False(即如果len(element)等於0)。這就意味著if element.find('...')並非在測試是否find()方法找到了匹配項;這條語句是在測試匹配到的元素是否包含子項目。想要測試find()方法是否返回了一個元素,則需使用if element.find('...') is not None。

>>> bk = res[0].find("no") >>> bk >>> type(bk) <class 'NoneType'> >>> res[0].find("id") <Element 'id' at 0x0000000003413CC8> >>> if res[0].find("id"):     print("find")   else:     print("not find") not find >>> if res[0].find("id") is not None:     print("find")   else:     print("not find") find 

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.