您好,登錄后才能下訂單哦!
Python使用ElementTree實現解析xml?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
以country.xml為例,內容如下:
<?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>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> </data>
1.解析
1)調用parse()方法,返回解析樹
try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET tree = ET.parse("country.xml") # <class 'xml.etree.ElementTree.ElementTree'> root = tree.getroot() # 獲取根節點 <Element 'data' at 0x02BF6A80>
2)調用from_string(),返回解析樹的根元素
import xml.etree.ElementTree as ET
data = open("country.xml").read()
root = ET.fromstring(data) # <Element 'data' at 0x036168A0>
3)調用ElementTree類ElementTree(self, element=None, file=None) # 這里的element作為根節點
import xml.etree.ElementTree as ET
tree = ET.ElementTree(file="country.xml") # <xml.etree.ElementTree.ElementTree object at 0x03031390>
root = tree.getroot() # <Element 'data' at 0x030EA600>
1)簡單遍歷
import xml.etree.ElementTree as ET tree = ET.parse("country.xml") root = tree.getroot() print(root.tag, ":", root.attrib) # 打印根元素的tag和屬性 # 遍歷xml文檔的第二層 for child in root: # 第二層節點的標簽名稱和屬性 print(child.tag,":", child.attrib) # 遍歷xml文檔的第三層 for children in child: # 第三層節點的標簽名稱和屬性 print(children.tag, ":", children.attrib)
可以通過下標的方式直接訪問節點
# 訪問根節點下第一個country的第二個節點year,獲取對應的文本
year = root[0][1].text # 2008
2)ElementTree提供的方法
find(match) # 查找第一個匹配的子元素, match可以時tag或是xpaht路徑
findall(match) # 返回所有匹配的子元素列表
findtext(match, default=None) #
iter(tag=None) # 以當前元素為根節點 創建樹迭代器,如果tag不為None,則以tag進行過濾
iterfind(match) #
例子:
# 過濾出所有neighbor標簽
for neighbor in root.iter("neighbor"):
print(neighbor.tag, ":", neighbor.attrib)
# 遍歷所有的counry標簽
for country in root.findall("country"):
# 查找country標簽下的第一個rank標簽
rank = country.find("rank").text
# 獲取country標簽的name屬性
name = country.get("name")
print(name, rank)
1) 屬性相關
# 將所有的rank值加1,并添加屬性updated為yes for rank in root.iter("rank"): new_rank = int(rank.text) + 1 rank.text = str(new_rank) # 必須將int轉為str rank.set("updated", "yes") # 添加屬性 # 再終端顯示整個xml ET.dump(root) # 注意 修改的內容存在內存中 尚未保存到文件中 # 保存修改后的內容 tree.write("output.xml")
import xml.etree.ElementTree as ET tree = ET.parse("output.xml") root = tree.getroot() for rank in root.iter("rank"): # attrib為屬性字典 # 刪除對應的屬性updated del rank.attrib['updated'] ET.dump(root)
小結: 關于classxml.etree.ElementTree.Element 屬性相關
2) 節點/元素 相關
刪除子元素remove()
import xml.etree.ElementTree as ET tree = ET.parse("country.xml") root = tree.getroot() # 刪除rank大于50的國家 for country in root.iter("country"): rank = int(country.find("rank").text) if rank > 50: # remove()方法 刪除子元素 root.remove(country) ET.dump(root)
添加子元素
代碼:
import xml.etree.ElementTree as ET tree = ET.parse("country.xml") root = tree.getroot() country = root[0] last_ele = country[len(list(country))-1] last_ele.tail = '\n\t\t' # 創建新的元素, tag為test_append elem1 = ET.Element("test_append") elem1.text = "elem 1" # elem.tail = '\n\t' country.append(elem1) # SubElement() 其實內部調用的時append() elem2 = ET.SubElement(country, "test_subelement") elem2.text = "elem 2" # extend() elem3 = ET.Element("test_extend") elem3.text = "elem 3" elem4 = ET.Element("test_extend") elem4.text = "elem 4" country.extend([elem3, elem4]) # insert() elem5 = ET.Element("test_insert") elem5.text = "elem 5" country.insert(5, elem5) ET.dump(country)
效果:
添加子元素方法總結:
4.創建xml文檔
想創建root Element,然后創建SubElement,最后將root element傳入ElementTree(element),創建tree,調用tree.write()方法寫入文件
對于創建元素的3個方法: 使用ET.Element、Element對象的makeelement()方法以及ET.SubElement
import xml.etree.ElementTree as ET def subElement(root, tag, text): ele = ET.SubElement(root, tag) ele.text = text ele.tail = '\n' root = ET.Element("note") to = root.makeelement("to", {}) to.text = "peter" to.tail = '\n' root.append(to) subElement(root, "from", "marry") subElement(root, "heading", "Reminder") subElement(root, "body", "Don't forget the meeting!") tree = ET.ElementTree(root) tree.write("note.xml", encoding="utf-8", xml_declaration=True)
效果:
由于原生保存的XML時默認無縮進,如果想要設置縮進的話, 需要修改保存方式
代碼:
import xml.etree.ElementTree as ET from xml.dom import minidom def subElement(root, tag, text): ele = ET.SubElement(root, tag) ele.text = text def saveXML(root, filename, indent="\t", newl="\n", encoding="utf-8"): rawText = ET.tostring(root) dom = minidom.parseString(rawText) with open(filename, 'w') as f: dom.writexml(f, "", indent, newl, encoding) root = ET.Element("note") to = root.makeelement("to", {}) to.text = "peter" root.append(to) subElement(root, "from", "marry") subElement(root, "heading", "Reminder") subElement(root, "body", "Don't forget the meeting!") # 保存xml文件 saveXML(root, "note.xml")
看完上述內容,你們掌握Python使用ElementTree實現解析xml的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。