第五周-第11章节-Python3.5-内置模块详解之Xml模块
Python XML操作
XML(可擴展性標記語言)是一種非常常用的文件類型,主要用于存儲和傳輸數據。在編程中,對XML的操作也非常常見。
本文根據python庫文檔中的xml.etree.ElementTree類來進行介紹XML的解析:https://docs.python.org/3.5/library/xml.etree.elementtree.html?
BTW,xml.etree.cElementTree模塊從3.3以后就被棄用了.
XML格式
首先,來看一下XML所包含的元素類型
1. 標簽 <tag>
2. 屬性 <tag ?name="attribute">
3. 數據 <data>1<data>
?例如 xml段:
<?xml version="1.0"?> <data><country name="Liechtenstein"><rank>1</rank><year>2008</year><gdppc>141100</gdppc><neighbor name="Austria" direction="E"/><neighbor name="Switzerland" direction="W"/></country><country name="Singapore"><rank>4</rank><year>2011</year><gdppc>59900</gdppc><neighbor name="Malaysia" direction="N"/></country><country name="Panama"><rank>68</rank><year>2011</year><gdppc>13600</gdppc><neighbor name="Costa Rica" direction="W"/><neighbor name="Colombia" direction="E"/></country> </data>?
XML操作
-
讀取
-
訪問
- 訪問Element對象的標簽、屬性和值
-
- 訪問子節點
-
查找操作
- Element元素迭代子元素:Element.iter("tag"),可以羅列該節點所包含的所有其他節點(element對象)
-
- Element.findall("tag"):查找當前元素為“tag”的直接子元素
-
- Element.find("tag"):查找為tag的第一個直接子元素
-
創建xml文件
創建的新文件內容為:<root><sub1 name="name attribute" /><sub2>test</sub2></root>
-
修改XML文件
- ElementTree.write("xmlfile"):更新xml文件
- Element.append():為當前element對象添加子元素(element)
- Element.set(key,value):為當前element的key屬性設置value值
- Element.remove(element):刪除為element的節點
更新完的文件為:<root><sub1 name="New Name" /><sub2>New Value</sub2><NewElement age="20" name="NewElement">This is a new element</NewElement></root>
?
總結
?XML的操作比較常見,當然也有很多第三方的庫可以使用,所需要做的操作無非就是常用的讀寫xml文件、元素節點的增刪改查,大家還可以在python官方文檔上學習更多的操作。
轉載于:https://www.cnblogs.com/pcjbk/p/11042740.html
總結
以上是生活随笔為你收集整理的第五周-第11章节-Python3.5-内置模块详解之Xml模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Cookie,Session
- 下一篇: linux中快速查找文件