python读取xml_python解析xml文件
加載和讀取xml文件
import xml.dom.minidom
doc = xml.dom.minidom.parse(xmlfile)
獲取xml文檔對象(對子節點和節點node都適用)
root = doc.documentElement
節點屬性
root.nodeName # 每個節點都有它的 nodeName,nodeValue, nodeType屬性;
root.nodeValue # nodeValue 是節點的值,只對本文本節點有效;
文本節點:
Element節點下面沒有別的節點,只有文本的話
txt_node = Element節點.firstChild
txt_node.data 或者 txt_node.nodeValue都是可以獲取文本
root.nodeType # 節點類型;
root.ELEMENT_NODE
屬性值的獲取、修改、刪除
root.getAttribute(attributeName) # 獲取 xml 節點屬性值;
root.setAttribute(attributeName, value) # 修改或添加 xml 節點屬性值;
root.getElementsByTagName(TagName) # 根據標簽獲取 xml 節點對象集合
root.removeAttribute(attributeName) # 刪除 xml 節點屬性值;
子節點的訪問
root.childNodes # 獲取子節點列表;
root.childNodes[index].nodeValue # 獲取 xml 節點值;
c # 訪問第一個節點(相當于 root.childNodes[0]);
root.childNodes[0].data # 獲得文本值;
刪除和生成節點
# 刪除 node 節點下面的子節點 childnode_in_node
node.removeChild(childnode_in_node)
# 生成節點 # 文本節點.createTextNode('xxxxx')
node.createElement('activity')
pass
通過xml.dom.minidom解析xml文件
"""
War, Thriller
DVD
2003
PG
10
Talk about a US-Japan war
Anime, Science Fiction
DVD
1989
R
8
A schientific fiction
Anime, Action
DVD
4
PG
10
Vash the Stampede!
Comedy
VHS
PG
2
Viewable boredom
"""
# 通過minidom解析xml文件
import xml.dom.minidom as xmldom
# get file object
doc = xmldom.parse(r'movie.xml') #
# get element object
root = doc.documentElement #
node1 = root.getElementsByTagName("movie") #
# get tab attribute
print(node1[0].getAttribute("title")) # Enemy Behind
movie = root.getElementsByTagName("movie")
print(movie[0].nodeName) # movie
print(movie[0].nodeType) # 1
print(movie[0].nodeValue) # None
print(movie[0].lastChild) #
year_list = root.getElementsByTagName("year")
print(year_list[0].firstChild.data) # 2003
print(year_list[0].nodeValue) # None
for i in range(len(year_list)):
print(year_list[i].lastChild)
#
#
#
#
print(year_list[0].firstChild.nodeValue) # 2003
name
age
shanpao
S12
總結
以上是生活随笔為你收集整理的python读取xml_python解析xml文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3编码转换_Python3编
- 下一篇: websocket receive方法内