Import module
import xml.etree.ElementTree as ET
Read parsing XML
Can be resolved from the string xml file
to create a new file xml
<?xml version="1.0" encoding="UTF-8"?> <students> <student> <name>张三</name> <age>18</age> <score>89</score> </student> <student> <name>李四</name> <age>19</age> <score>81</score> </student> <student> <name>王五</name> <age>17</age> <score>92</score> </student> </students>
Xml file read from using getRoot () Gets the root, an Element object is obtained
tree = ET.parse('students.xml')
root = tree.getroot()
Read from the string variable, the Element object is returned
root = ET.fromstring(country_data_as_string)
Access XML
Each Element has the following properties
#tag = element.text #访问Element标签
#attrib = element.attrib #访问Element属性
#text = element.text #访问Element文本
for element in root.findall('student'): tag = element.tag #访问Element标签 attrib = element.attrib #访问Element属性 text = element.find('name').text #访问Element文本 print(tag, attrib, text) print(root[0][0].text) #子节点是嵌套的,我们可以通关索引访问特定的子节点
Finding Elements
Element provides a number of ways to help us to traverse of his child node
1、Element.iter()
for student in root.iter('student'):
print student[0].text out: 张三 李四 王五
2、Element.findall()
for element in root.findall('student'):
name = element.find('name').text
age = element.find('age').text score = element.find('score').text print name,age,score out: 张三 18 89 李四 19 81 王五 17 92
Modify XML
- ElementTree.write () will build the XML document written to the file.
- Element.text = '' to directly change the contents of the field
- Element.append (Element) add a child object objects for the current Elment
- Element.remove (Element) Delete Element node
- Element.set (key, value) add and modify attributes
- ElementTree.write ( 'filename.xml') write (update) XMl file
Creating XML
- ElementTree.Element () Construction of a node
- ElementTree.SubElement (Element, tag) to build a child node
a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
print ET.dump(a)
out:
<a><b /><c /></a>
to sum up
Recently wrote things are needed output xml, so learning the use of XML and XML in the python. More can be seen official documentation.