Python是非常強大的工具,用它解析XML非常快速,而且可以迅速的處理自己想要的數據,以下是示例代碼:
import xml.etree.ElementTree as etree
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
def is_info_in_xml( xml_filename):
'''精確檢查XML文檔中被查找信息是否存在'''
info_exists = False
xml_document = etree.parse(xml_filename)
root = xml_document.getroot() # 獲取根元素
# print('xml file root:', root) # 獲取根名稱
# print('root:%s' % root ) # 獲取根元素的屬性集
# print('%s %s="%s"' % (root.tag, root.tag, root.attrib) ) # 獲取根元素的屬性集
# print('root len:', len(root)) # 獲取根元素的長度(也就是根元素下的子元素的個數)
# 檢查root節點下的所有子節點
for softwarelist in root: # 處理下一級子節點SoftwareList
# print('\t%s' % softwarelist.tag, end = ' ')
for attrname in softwarelist.attrib:
# print('%s="%s"' % (attrname, softwarelist.attrib[attrname]), end = ' ') # 獲取元素的屬性集
pass
# print()
for group in softwarelist: # 處理下一級子節點Group
# print('\t%s' % group.tag, end = ' ')
for attrname in group.attrib:
# print('%s="%s"' % (attrname, group.attrib[attrname]), end = ' ') # 獲取元素的屬性集
pass
# print()
for software in group: # 處理下一級子節點Software
# print('\t\t%s' % software.tag)
for attrname in software.attrib:
# print('\t\t\t%s="%s"' % (attrname, software.attrib[attrname])) # 獲取元素的屬性集
if '查找字符串' in software.attrib[attrname]:
info_exists = True
# print()
return info_exists
推薦閱讀:
《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm
Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm
Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡