欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python如何使用ElementTree解析xml

程序员文章站 2023-12-24 12:40:15
以country.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 属性相关

  • attrib    为包含元素属性的字典
  • keys() 返回元素属性名称列表
  • items() 返回(name,value)列表
  • get(key, default=none) 获取属性
  • set(key, value) # 跟新/添加 属性
  • del xxx.attrib[key] # 删除对应的属性

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)

效果:

Python如何使用ElementTree解析xml

添加子元素方法总结:

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

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)

效果:

Python如何使用ElementTree解析xml

由于原生保存的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")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: