#! /usr/bin/env python
#-*-Coding:utf-8-*-
Import XML
Import requests
From xml.etree import ElementTree as ET
# 1. Reading an XML file as a string
page = open (' Blog.xml ', ' R ', encoding= ' utf-8 '). Read ()
root = et. XML (page)
Print (root.tag) # tag name of the current node tag
For node in root:
Print (Node.tag,node.attrib,node.find (' year '). Text)
#当前节点的属性 attrib
#当前节点的内容 text
# #2. open file as parse file to modify file contents
Tree = Et.parse (' Blog.xml ')
Rot = Tree.getroot ()
For nod in Rot.iter (' year '):
new_year = Int (nod.text) +1
Nod.text = str (new_year)
# Set (self, key, value): Set property
# Get (self, Key, Default=none): Gets the property value of the current node
Nod.set (' name ', ' NF ')
# Delete Properties
Del nod.attrib[' name ']
Print (dir (rot)) # See which methods are available under this layer node
# Append (self, subelement): Appends a child node to the current node
# Extend (self, elements): Expands n child nodes for the current node
# Insert (self, Index, subelement): Inserts a node in the child node of the current node,
# that is: Create a child node for the current node and insert the specified location
#remove (self, subelement): Removes a node from a child node in the current node
# FindAll (self, Path, namespaces=none): Get all child nodes
# Iterfind (self, Path, Namespaces=none):
# gets all the specified nodes and creates an iterator (which can be used for loops)
# Clear (Self): empty node
#
Tree.write (' Blog.xml ')
# #3. Creating an XML file
#创建节点有三种方式:
# #1) makeelement (self, Tag, attrib): Create a new node
# #2) Element (tag, attrib={}): Create a node
# #3) subelement (parent, tag, attrib={}, **extra) is used to construct a child node of an already existing node
#创建根节点
FA = et. Element ("Father")
#创建子节点
S1 = et. Element (' son ', {' name ': "eldest son"})
S2 = fa.makeelement (' son ', {' name ': ' Second Son '})
S3 = et. subelement (FA, ' son ', attrib={' name ': "Three Sons"})
#将子节点添加到父节点
Fa.append (S1)
Fa.append (S2)
#prettify (elem): Converts a node to a string and adds an indent
#生成文档对象, writing documents
ZP = et. ElementTree (FA)
Zp.write ("Zp.xml", encoding= ' Utf-8 ', short_empty_elements=false)
Python XML module