1. 背景說明?
解析 xml 格式的文件有多種方法, 這里只介紹使用 xml.etree.ElementTree 這種解析方式.
2. ElementTree 和 cElementTree 的區別?
ElementTree在 Python 標准庫中有兩種實現。一種是純 Python 實現例如 xml.etree.ElementTree ,另外一種是速度快一點的 xml.etree.cElementTree 。你要記住: 盡量使用 C 語言實現的那種,因為它速度更快,而且消耗的內存更少。
注意: 開發的時候為了調試方便, 可以使用 ElementTree .
3. 解析方式?
導入包: python3.3之后ElementTree模塊會自動尋找可用的C庫來加快速度
try: import xml.etree.cElementTree as et except ImportError: import xml.etree.ElementTree as et
3.1 方式一: 讀取 xml 文件成 xml 對象
# 從某文件解析成 xml 對象: tree_obj = et.parse( "city_info.xml" ) # 獲取根節點元素 root = tree_obj.getroot()
3.2 方式二: 讀取 xml 字符串成 xml 對象
# 注意: xml 格式開頭的 <?xml version...... 一定不能有空格, 否則報錯!!! xml_text = """<?xml version="1.0" encoding="UTF-8"?> <struts> <action name="login" class="com.coderising.litestruts.LoginAction"> <result name="success">homepage.jsp</result> <result name="fail">showLogin.jsp</result> </action> <action name="logout" class="com.coderising.litestruts.LogoutAction"> <result name="success">welcome.jsp</result> <result name="error">error.jsp</result> </action> </struts> """ # 獲取很節點元素 root = et.fromstring(xml_text)
3.3 解析各元素獲取信息
獲取屬性值和文本信息
# xml_text, 即上面的xml字符串 root = et.fromstring(xml_text) for action in root.iter("action"): act_name = action.attrib.get("name") # 獲取屬性值 class_info = action.get("class") # 同樣也是獲取標簽屬性值, 上面的簡寫方式 for result in action.iter("result"): res_name = result.get("name") res_text = result.text # 獲取標簽文本信息
find 方法 + xpath 解析式 (注意: xpath解析式不支持絕對路徑, 僅支持相對路徑, 比如 "./")
find(): 查找滿足條件的第一個標簽
findall(): 查找滿足條件的所有標簽
root = et.fromstring(xml_text) # find() 查找第一個標簽 action = root.find(".//action/result[2]") print(action.get("name")) # fail print(action.text) # result 1.2 result 1.2 result 1.2 result 1.2 # findall() 查找所有標簽 actions = root.findall(".//action/result") for action in actions: ac_name = action.get("name") ac_text = action.text