日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 之 XML的基本应用总结

發布時間:2023/12/20 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的基本应用总结的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。