python 之 XML的基本应用总结
生活随笔
收集整理的這篇文章主要介紹了
python 之 XML的基本应用总结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.XML 的特征:xml即可擴展標記語言,它可以用來標記數據、定義數據類型,是一種允許用戶對自己的標記語言進行定義的源語言。從結構上,很像HTML超文本標記語言。但他們被設計的目的是不同的,超文本標記語言被設計用來顯示數據,其焦點是數據的外觀。它被設計用來傳輸和存儲數據,其焦點是數據的內容
?
那么它有如下特征:
?
- 它是有標簽對組成,<aa></aa>
- 標簽可以有屬性:<aa id='123'></aa>
- 標簽對可以嵌入數據:<aa>abc</aa>
- 標簽可以嵌入子標簽(具有層級關系)
?
例子:創建一個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>?
步驟:
【XML操作】
?
import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml") root = tree.getroot() print(root.tag)#遍歷xml文檔 for child in root:print(child.tag, child.attrib)for i in child:print(i.tag,i.text)#只遍歷year 節點 for node in root.iter('year'):print(node.tag,node.text) #修改和刪除xml文檔內容 import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml") root = tree.getroot()#修改 for node in root.iter('year'):new_year = int(node.text) + 1node.text = str(new_year)node.set("updated","yes")tree.write("xmltest.xml")#刪除node for country in root.findall('country'):rank = int(country.find('rank').text)if rank > 50:root.remove(country)tree.write('output.xml')【自己創建xml文檔】
import xml.etree.ElementTree as ETnew_xml = ET.Element("namelist") name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"}) age = ET.SubElement(name,"age",attrib={"checked":"no"}) sex = ET.SubElement(name,"sex") sex.text = '33' name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"}) age = ET.SubElement(name2,"age") age.text = '19'et = ET.ElementTree(new_xml) #生成文檔對象 et.write("test.xml", encoding="utf-8",xml_declaration=True)ET.dump(new_xml) #打印生成的格式?總結
minidom.parse(filename) 加載讀取XML文件doc.documentElement 獲取XML文檔對象node.getAttribute(AttributeName) 獲取XML節點屬性值node.getElementsByTagName(TagName) 獲取XML節點對象集合node.childNodes #返回子節點列表。 node.childNodes[index].nodeValue 獲取XML節點值node.firstChild #訪問第一個節點。等價于pagexml.childNodes[0] doc = minidom.parse(filename) doc.toxml('UTF-8') 返回Node節點的xml表示的文本Node.attributes["id"] a.name #就是上面的 "id" a.value #屬性的值 訪問元素屬性?
?
轉載于:https://www.cnblogs.com/lanyinhao/p/9176274.html
總結
以上是生活随笔為你收集整理的python 之 XML的基本应用总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅学JavaScript
- 下一篇: python——前端常用的标签