Article From:https://www.cnblogs.com/hexiaoqi/p/9378660.html

xmlModular

xmlExtensible Markup Language (XML) is similar to HTML in that it is used to transfer and store data. The module that processes XML data in Python is xml. etree. ElementTree.ElementTreeIt means node tree, and two Element brings a separate node.

xmlData are marked by labels and there are two kinds of labels.

Self closing label (head to tail):<age>2</age>

Unclosed tags (with no end):<husband age=”5″ name=”Mary” />

Look at the following XML data:

 

<data>
    <animals name="Tom">
        <age>2</age>
        <b_year>2010</b_year>
        <weight>20</weight>
        <husband age="10" name="Alex" />
    </animals>
    <animals name="Bob">
        <age>3</age>
        <b_year>2012</b_year>
        <weight>15</weight>
        <husband age="5" name="Mary" />
    </animals>
    <animals name="Chirwy">
        <age>4</age>
        <b_year>2008</b_year>
        <weight>25</weight>
        <husband age="3" name="Ared" />
    </animals>

</data>

 

1.Import XML module and parse XML file

1 import xml.etree.ElementTree as ET
2 
3 tree = ET.parse('XML_data')    #Parse XML_data to get the XLM data tree, assign it to tree to get an object, and then manipulate it directly
4 root = tree.getroot()    #Get root node
5 print(root)              #Print memory address of root node
6 print(root.tag)          #tagMethod to print the label name of the root node.

2.View other nodes and their names

 1 import xml.etree.ElementTree as ET
 2 
 3 tree = ET.parse('XML_data')    #Parse XML_data to get the XLM data tree, assign it to tree to get an object, and then manipulate it directly
 4 root = tree.getroot()    #Get root node
 5 print(root)              #Print memory address of root node
 6 print(root.tag)          #tagProperty to print the label name of the root node.
 7 
 8 for i in root:
 9     print("Subnode",i.tag)
10     for j in i:
11         print("Sun node", j.tag)

Result:

Child node animalsSun node ageSun node b_yearSun node weightSun node husbandChild node animalsSun node ageSun node b_yearSun node weightSun nodeHusbandChild node animalsSun node ageSun node b_yearSun node weightSun node husband

3.Get the attributes in the label

1 for m in root:
2     print(m.attrib)
{'name': 'Tom'}
{'name': 'Bob'}
{'name': 'Chirwy'}

4.The text content contained in the label

1 for m in root:
2     for n in m:
3         print(n.text)
2
2010
20
None
3
2012
15
None
4
2008
25
None

5.If you want to get the value in a specific tag, you can use the ITER () method.

1 for n in root.iter("b_year"):
2     print(n.tag,n.text)
b_year 2010
b_year 2012
b_year 2008

6.Modifying XML data

set()Method can add new attributes to labels.

1 for n in root.iter("b_year"):
2     new_year=int(n.text)+1
3     n.text=str(new_year)#Modify the text attribute of the b_year tag
4     n.set("updated1","yes")#Add an attribute to the year tag.
5 tree.write("xml_data1.xml")#Write the modification directly to the file.

The filename in the fifth line can use the original filename equivalent to overwrite updates, and he can use other names, equivalent to creating a new XML file.

7.Delete the tag using the remove () method, using the same method as 6.

8.Creating XML files through modules

1 import xml.etree.ElementTree as ET     #Import module
2 new_xml = ET.Element('Student')     #Create root node
3 name = ET.SubElement(new_xml, 'name', attrib={"GPA":'4.5'}) #Create child nodes
4 age = ET.SubElement(name, 'age',attrib={'isOK':'ok'})       #Create sun node
5 sex = ET.SubElement(name, 'sex')                #Create sun node
6 sex.text = '28'                                 #Add label content
7 
8 et = ET.ElementTree(new_xml)            #Generating file objects
9 et.write('test.xml', encoding='utf-8',xml_declaration=True)     #Generating object

Result:

<?xml version='1.0' encoding='utf-8'?>
<Student>
    <name GPA="4.5">
        <age isOK="ok" />
        <sex>28</sex>
    </name>
</Student>

 

Link of this Article: XML module

Leave a Reply

Your email address will not be published. Required fields are marked *