溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python使用ElementTree實(shí)現(xiàn)解析xml

發(fā)布時(shí)間:2020-10-28 16:23:08 來(lái)源:億速云 閱讀:219 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

Python使用ElementTree實(shí)現(xiàn)解析xml?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

以country.xml為例,內(nèi)容如下:

<&#63;xml version="1.0"&#63;>
<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)調(diào)用parse()方法,返回解析樹(shù)

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()      # 獲取根節(jié)點(diǎn) <Element 'data' at 0x02BF6A80>

2)調(diào)用from_string(),返回解析樹(shù)的根元素

import xml.etree.ElementTree as ET
data = open("country.xml").read()
root = ET.fromstring(data) # <Element 'data' at 0x036168A0>

3)調(diào)用ElementTree類(lèi)ElementTree(self, element=None, file=None) # 這里的element作為根節(jié)點(diǎn)

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)簡(jiǎn)單遍歷

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:
  # 第二層節(jié)點(diǎn)的標(biāo)簽名稱(chēng)和屬性
  print(child.tag,":", child.attrib) 
  # 遍歷xml文檔的第三層
  for children in child:
    # 第三層節(jié)點(diǎn)的標(biāo)簽名稱(chēng)和屬性
    print(children.tag, ":", children.attrib)

可以通過(guò)下標(biāo)的方式直接訪問(wèn)節(jié)點(diǎn)

# 訪問(wèn)根節(jié)點(diǎn)下第一個(gè)country的第二個(gè)節(jié)點(diǎn)year,獲取對(duì)應(yīng)的文本
year = root[0][1].text # 2008

2)ElementTree提供的方法

find(match) # 查找第一個(gè)匹配的子元素, match可以時(shí)tag或是xpaht路徑
findall(match) # 返回所有匹配的子元素列表
findtext(match, default=None) #
iter(tag=None) # 以當(dāng)前元素為根節(jié)點(diǎn) 創(chuàng)建樹(shù)迭代器,如果tag不為None,則以tag進(jìn)行過(guò)濾
iterfind(match) #

例子:

# 過(guò)濾出所有neighbor標(biāo)簽
for neighbor in root.iter("neighbor"):
print(neighbor.tag, ":", neighbor.attrib)

# 遍歷所有的counry標(biāo)簽
for country in root.findall("country"):
# 查找country標(biāo)簽下的第一個(gè)rank標(biāo)簽
rank = country.find("rank").text
# 獲取country標(biāo)簽的name屬性
name = country.get("name")
print(name, rank)

1) 屬性相關(guān)

# 將所有的rank值加1,并添加屬性u(píng)pdated為yes
for rank in root.iter("rank"):
  new_rank = int(rank.text) + 1
  rank.text = str(new_rank) # 必須將int轉(zhuǎn)為str
  rank.set("updated", "yes") # 添加屬性

# 再終端顯示整個(gè)xml
ET.dump(root)
# 注意 修改的內(nèi)容存在內(nèi)存中 尚未保存到文件中
# 保存修改后的內(nèi)容
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為屬性字典
  # 刪除對(duì)應(yīng)的屬性u(píng)pdated
  del rank.attrib['updated'] 

ET.dump(root)

小結(jié): 關(guān)于classxml.etree.ElementTree.Element 屬性相關(guān)

  • attrib    為包含元素屬性的字典
  • keys() 返回元素屬性名稱(chēng)列表
  • items() 返回(name,value)列表
  • get(key, default=None) 獲取屬性
  • set(key, value) # 跟新/添加 屬性
  • del xxx.attrib[key] # 刪除對(duì)應(yīng)的屬性

2) 節(jié)點(diǎn)/元素 相關(guān)

刪除子元素remove()

import xml.etree.ElementTree as ET

tree = ET.parse("country.xml")
root = tree.getroot()

# 刪除rank大于50的國(guó)家
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'
# 創(chuàng)建新的元素, tag為test_append
elem1 = ET.Element("test_append")
elem1.text = "elem 1"
# elem.tail = '\n\t'
country.append(elem1)

# SubElement() 其實(shí)內(nèi)部調(diào)用的時(shí)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)

效果:

Python使用ElementTree實(shí)現(xiàn)解析xml

添加子元素方法總結(jié):

  • append(subelement)
  • extend(subelements)
  • insert(index, element)

4.創(chuàng)建xml文檔

想創(chuàng)建root Element,然后創(chuàng)建SubElement,最后將root element傳入ElementTree(element),創(chuàng)建tree,調(diào)用tree.write()方法寫(xiě)入文件

對(duì)于創(chuàng)建元素的3個(gè)方法: 使用ET.Element、Element對(duì)象的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)

效果:

Python使用ElementTree實(shí)現(xiàn)解析xml

由于原生保存的XML時(shí)默認(rèn)無(wú)縮進(jìn),如果想要設(shè)置縮進(jìn)的話, 需要修改保存方式

代碼:

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")

看完上述內(nèi)容,你們掌握Python使用ElementTree實(shí)現(xiàn)解析xml的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI