python处理XML文件

解析XML

利用ElementTree.XML将字符串解析成xml对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from xml.etree import ElementTree as ET

# 打开文件,读取XML内容
str_xml = open('xo.xml', 'r').read()
print(str_xml, type(str_xml))
# 将字符串解析成xml特殊对象,root代指xml文件的根节点
root = ET.XML(str_xml)
print(root, type(root))

------------
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2023</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2026</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2026</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data> <class 'str'>
<Element 'data' at 0x101383cc8> <class 'xml.etree.ElementTree.Element'>

从结果中可以看出,root变量获取到了xml文件的根节点信息,且数据类型为xml.etree.ElementTree.Element

利用ElementTree.parse将文件解析成xml对象

1
2
3
4
5
6
7
8
9
10
11
12
from xml.etree import ElementTree as ET

# 直接解析xml文件
tree = ET.parse("xo.xml")
print(tree, type(tree)
# 获取xml文件的根节点
root = tree.getroot()
print(root, type(root))

------------
<xml.etree.ElementTree.ElementTree object at 0x101178780> <class 'xml.etree.ElementTree.ElementTree'>
<Element 'data' at 0x101283cc8> <class 'xml.etree.ElementTree.Element'>

两种解析方式的区别

读取字符串和读取文件的方式的区别:

  • 读取字符串的方式没有创建tree对象

  • 读取文件的方式自动创建了tree对象

而如果需要将在内存修改过的element对象保存成文件的时候,就必须需要用tree对象的write方法来写。

如果直接读取了字符串,默认没有创建tree对象,那么在需要写入到本地文件时,就必须先创建tree对象再进行写入

操作XML

每一个节点就是一个element对象,每一个element对象都有如下方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
class Element:
"""An XML element.

This class is the reference implementation of the Element interface.

An element's length is its number of subelements. That means if you
want to check if an element is truly empty, you should check BOTH
its length AND its text attribute.

The element tag, attribute names, and attribute values can be either
bytes or strings.

*tag* is the element name. *attrib* is an optional dictionary containing
element attributes. *extra* are additional element attributes given as
keyword arguments.

Example form:
<tag attrib>text<child/>...</tag>tail

"""

当前节点的标签名
tag = None
"""The element's name."""

当前节点的属性

attrib = None
"""Dictionary of the element's attributes."""

当前节点的内容
text = None
"""
Text before first subelement. This is either a string or the value None.
Note that if there is no text, this attribute may be either
None or the empty string, depending on the parser.

"""

tail = None
"""
Text after this element's end tag, but before the next sibling element's
start tag. This is either a string or the value None. Note that if there
was no text, this attribute may be either None or an empty string,
depending on the parser.

"""

def __init__(self, tag, attrib={}, **extra):
if not isinstance(attrib, dict):
raise TypeError("attrib must be dict, not %s" % (
attrib.__class__.__name__,))
attrib = attrib.copy()
attrib.update(extra)
self.tag = tag
self.attrib = attrib
self._children = []

def __repr__(self):
return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))

def makeelement(self, tag, attrib):
创建一个新节点
"""Create a new element with the same type.

*tag* is a string containing the element name.
*attrib* is a dictionary containing the element attributes.

Do not call this method, use the SubElement factory function instead.

"""
return self.__class__(tag, attrib)

def copy(self):
"""Return copy of current element.

This creates a shallow copy. Subelements will be shared with the
original tree.

"""
elem = self.makeelement(self.tag, self.attrib)
elem.text = self.text
elem.tail = self.tail
elem[:] = self
return elem

def __len__(self):
return len(self._children)

def __bool__(self):
warnings.warn(
"The behavior of this method will change in future versions. "
"Use specific 'len(elem)' or 'elem is not None' test instead.",
FutureWarning, stacklevel=2
)
return len(self._children) != 0 # emulate old behaviour, for now

def __getitem__(self, index):
return self._children[index]

def __setitem__(self, index, element):
# if isinstance(index, slice):
# for elt in element:
# assert iselement(elt)
# else:
# assert iselement(element)
self._children[index] = element

def __delitem__(self, index):
del self._children[index]

def append(self, subelement):
为当前节点追加一个子节点
"""Add *subelement* to the end of this element.

The new element will appear in document order after the last existing
subelement (or directly after the text, if it's the first subelement),
but before the end tag for this element.

"""
self._assert_is_element(subelement)
self._children.append(subelement)

def extend(self, elements):
为当前节点扩展 n 个子节点
"""Append subelements from a sequence.

*elements* is a sequence with zero or more elements.

"""
for element in elements:
self._assert_is_element(element)
self._children.extend(elements)

def insert(self, index, subelement):
在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置
"""Insert *subelement* at position *index*."""
self._assert_is_element(subelement)
self._children.insert(index, subelement)

def _assert_is_element(self, e):
# Need to refer to the actual Python implementation, not the
# shadowing C implementation.
if not isinstance(e, _Element_Py):
raise TypeError('expected an Element, not %s' % type(e).__name__)

def remove(self, subelement):
在当前节点在子节点中删除某个节点
"""Remove matching subelement.

Unlike the find methods, this method compares elements based on
identity, NOT ON tag value or contents. To remove subelements by
other means, the easiest way is to use a list comprehension to
select what elements to keep, and then use slice assignment to update
the parent element.

ValueError is raised if a matching element could not be found.

"""
# assert iselement(element)
self._children.remove(subelement)

def getchildren(self):
获取所有的子节点(废弃)
"""(Deprecated) Return all subelements.

Elements are returned in document order.

"""
warnings.warn(
"This method will be removed in future versions. "
"Use 'list(elem)' or iteration over elem instead.",
DeprecationWarning, stacklevel=2
)
return self._children

def find(self, path, namespaces=None):
获取第一个寻找到的子节点
"""Find first matching element by tag name or path.

*path* is a string having either an element tag or an XPath,
*namespaces* is an optional mapping from namespace prefix to full name.

Return the first matching element, or None if no element was found.

"""
return ElementPath.find(self, path, namespaces)

def findtext(self, path, default=None, namespaces=None):
获取第一个寻找到的子节点的内容
"""Find text for first matching element by tag name or path.

*path* is a string having either an element tag or an XPath,
*default* is the value to return if the element was not found,
*namespaces* is an optional mapping from namespace prefix to full name.

Return text content of first matching element, or default value if
none was found. Note that if an element is found having no text
content, the empty string is returned.

"""
return ElementPath.findtext(self, path, default, namespaces)

def findall(self, path, namespaces=None):
获取所有的子节点
"""Find all matching subelements by tag name or path.

*path* is a string having either an element tag or an XPath,
*namespaces* is an optional mapping from namespace prefix to full name.

Returns list containing all matching elements in document order.

"""
return ElementPath.findall(self, path, namespaces)

def iterfind(self, path, namespaces=None):
获取所有指定的节点,并创建一个迭代器(可以被for循环)
"""Find all matching subelements by tag name or path.

*path* is a string having either an element tag or an XPath,
*namespaces* is an optional mapping from namespace prefix to full name.

Return an iterable yielding all matching elements in document order.

"""
return ElementPath.iterfind(self, path, namespaces)

def clear(self):
清空节点
"""Reset element.

This function removes all subelements, clears all attributes, and sets
the text and tail attributes to None.

"""
self.attrib.clear()
self._children = []
self.text = self.tail = None

def get(self, key, default=None):
获取当前节点的属性值
"""Get element attribute.

Equivalent to attrib.get, but some implementations may handle this a
bit more efficiently. *key* is what attribute to look for, and
*default* is what to return if the attribute was not found.

Returns a string containing the attribute value, or the default if
attribute was not found.

"""
return self.attrib.get(key, default)

def set(self, key, value):
为当前节点设置属性值
"""Set element attribute.

Equivalent to attrib[key] = value, but some implementations may handle
this a bit more efficiently. *key* is what attribute to set, and
*value* is the attribute value to set it to.

"""
self.attrib[key] = value

def keys(self):
获取当前节点的所有属性的 key

"""Get list of attribute names.

Names are returned in an arbitrary order, just like an ordinary
Python dict. Equivalent to attrib.keys()

"""
return self.attrib.keys()

def items(self):
获取当前节点的所有属性值,每个属性都是一个键值对
"""Get element attributes as a sequence.

The attributes are returned in arbitrary order. Equivalent to
attrib.items().

Return a list of (name, value) tuples.

"""
return self.attrib.items()

def iter(self, tag=None):
在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。
"""Create tree iterator.

The iterator loops over the element and all subelements in document
order, returning all elements with a matching tag.

If the tree structure is modified during iteration, new or removed
elements may or may not be included. To get a stable set, use the
list() function on the iterator, and loop over the resulting list.

*tag* is what tags to look for (default is to return all elements)

Return an iterator containing all the matching elements.

"""
if tag == "*":
tag = None
if tag is None or self.tag == tag:
yield self
for e in self._children:
yield from e.iter(tag)

# compatibility
def getiterator(self, tag=None):
# Change for a DeprecationWarning in 1.4
warnings.warn(
"This method will be removed in future versions. "
"Use 'elem.iter()' or 'list(elem.iter())' instead.",
PendingDeprecationWarning, stacklevel=2
)
return list(self.iter(tag))

def itertext(self):
在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。
"""Create text iterator.

The iterator loops over the element and all subelements in document
order, returning all inner text.

"""
tag = self.tag
if not isinstance(tag, str) and tag is not None:
return
if self.text:
yield self.text
for e in self:
yield from e.itertext()
if e.tail:
yield e.tail

遍历XML文档的所有内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from xml.etree import ElementTree as ET

# 直接解析xml文件
tree = ET.parse("xo.xml")

# 获取xml文件的根节点
root = tree.getroot()

# 获取顶层标签
print(root.tag)

# 遍历xml文档的第二层
for i in root:
# 第二层节点的标签名称和标签属性
print(i.tag, i.attrib)
# 遍历xml文档的第三层
for j in i:
print(j.tag, j.text)

------------
data
country {'name': 'Liechtenstein'}
rank 2
year 2023
gdppc 141100
neighbor None
neighbor None
country {'name': 'Singapore'}
rank 5
year 2026
gdppc 59900
neighbor None
country {'name': 'Panama'}
rank 69
year 2026
gdppc 13600
neighbor None
neighbor None

遍历指定节点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from xml.etree import ElementTree as ET

# 直接解析xml文件
tree = ET.parse("xo.xml")

# 获取xml文件的根节点
root = tree.getroot()

# 获取顶层标签
print(root.tag)

# root.iter()的参数中可以填入任意一个节点名称
for node in root.iter("gdppc"):
# 节点的标签名称和内容
print(node.tag, node.text)

------------
data
gdppc 141100
gdppc 59900
gdppc 13600

修改节点的内容

由于修改节点时,均是在内存中进行,不会影响到文件中的内容。所以如果想要修改,则需要重新将内存中的内容写入到文件。

  • 解析字符创的方式来修改和保存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from xml.etree import ElementTree as ET

# 打开文件,将文件的内容读到内存中
str_xml = open("xo.xml", 'r').read()

# 将字符串解析成xml特殊对象,root代指xml文件的根节点
root = ET.XML(str_xml)


# 开始操作xml对象
# 打印一下顶层的标签
print(root.tag)

# 循环所有的year节点
for node in root.iter("year"):
# 将year节点中的内容自增一
new_year = int(node.text) + 1
node.text = str(new_year)

# 设置属性
node.set("name", "polarsnow")
node.set("age", "25")

# 删除属性
del node.attrib["age"]

# 保存文件
## 使用读取字符串的方式在保存之前需要先创建ElementTree对象
tree = ET.ElementTree(root)
tree.write("newxo.xml", encoding="utf-8")
  • 解析文件的方式来修改和保存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from xml.etree import ElementTree as ET

# 直接解析xml文件
tree = ET.parse("xo.xml")

# 获取xml文件的根节点
root = tree.getroot()

# 开始操作xml对象
# 顶层标签
print(root.tag)

# 循环所有的year节点
for node in root.iter("year"):
# 将year节点中的内容自增一
new_year = int(node.text) + 1
node.text = str(new_year)

# 设置属性
node.set("name", "polarsnow")
node.set("age", "25")

# 删除属性
del node.attrib["age"]

# 保存文件
## 使用parse的方式直接解析xml文件,已经生成了ElementTree对象
## 可以直接调用写的方法
tree.write("newxo.xml", encoding="utf-8")
  • xo.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2023</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2026</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2026</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>
  • newxo.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year name="polarsnow">2024</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year name="polarsnow">2027</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year name="polarsnow">2027</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>

删除节点

  • 解析字符串的方式来删除节点
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from xml.etree import ElementTree as ET

# 打开文件,读取XML内容
str_xml = open('xo.xml', 'r').read()

# 将字符串解析成xml特殊对象,root代指xml文件的根节点
root = ET.XML(str_xml)

# 开始操作xml对象
# 顶层标签
print(root.tag)

# 遍历data下的所有country节点
for country in root.findall('country'):
# 获取每一个country节点下rank节点的内容
rank = int(country.find('rank').text)

if rank > 50:
# 删除指定country节点
root.remove(country)

# 保存文件
tree = ET.ElementTree(root)
tree.write("newxo.xml", encoding='utf-8')
  • 解析文件的方式来删除节点
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from xml.etree import ElementTree as ET

# 直接解析xml文件
tree = ET.parse("xo.xml")

# 获取xml文件的根节点
root = tree.getroot()

# 开始操作xml对象
# 顶层标签
print(root.tag)

# 遍历data下的所有country节点
for country in root.findall('country'):
# 获取每一个country节点下rank节点的内容
rank = int(country.find('rank').text)

if rank > 50:
# 删除指定country节点
root.remove(country)

# 保存文件
tree.write("newnew.xml", encoding='utf-8')

创建xml文档

  • 第一种创建方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element("World")

# 创建二级节点
country1 = ET.Element("country", {"name": "China"})
country2 = ET.Element("country", {"name": "America"})

# 创建三级节点
city1 = ET.Element("city", {"name": "BeiJing"})
city2 = ET.Element("city", {"name": "TangShan"})

# 把创建的三级节点添加到二级节点下面
country1.append(city1)
country1.append(city2)

# 再把二级节点添加到跟节点中
root.append(country1)
root.append(country2)

# 创建ElementTree对象
tree = ET.ElementTree(root)
tree.write("xxxx.xml", encoding="utf-8", short_empty_elements=False)

  • 第二种创建方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element("World")

# 创建二级节点
country1 = root.makeelement("country", {"name": "China"})
country2 = root.makeelement("country", {"name": "America"})

# 创建三级节点
city1 = country1.makeelement("city", {"name": "BeiJing"})
city2 = country1.makeelement("city", {"name": "TangShan"})

# 把创建的三级节点添加到二级节点下面
country1.append(city1)
country1.append(city2)

# 再把二级节点添加到跟节点中
root.append(country1)
root.append(country2)

# 创建ElementTree对象
tree = ET.ElementTree(root)
tree.write("xxxx.xml", encoding="utf-8", short_empty_elements=False)
  • 第三种创建方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element("World")

# 创建二级节点
country1 = ET.SubElement(root, "country", attrib={"name": "China"})
country2 = ET.SubElement(root, "country", attrib={"name": "America"})

# 创建三级节点
city1 = ET.SubElement(country1, "city", attrib={"name": "BeiJing"})
city2 = ET.SubElement(country1, "city", attrib={"name": "TangShan"})

et = ET.ElementTree(root) # 生成文档对象
# xml_declaration 添加xml版本信息注释
et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False)

第三种方式不同于上面两种方式的是在创建节点的时候,已经指定了该节点与其他节点的关系。

  • 缩进

原生保存的XML默认没有缩进,如果需要缩进,可以使用如下方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from xml.etree import ElementTree as ET
from xml.dom import minidom


def prettify(elem):
"""将节点转换成字符串,并添加缩进"""
rough_string = ET.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")

# 创建根节点
root = ET.Element("World")

# 创建二级节点
country1 = ET.SubElement(root, "country", attrib={"name": "China"})
country2 = ET.SubElement(root, "country", attrib={"name": "America"})

# 创建三级节点
city1 = ET.SubElement(country1, "city", attrib={"name": "BeiJing"})
city2 = ET.SubElement(country1, "city", attrib={"name": "TangShan"})

raw_str = prettify(root)

with open("xxoo.xml", 'w', encoding="utf-8") as f:
f.write(raw_str)