python的xml檔案操作

2022-05-01 12:57:05 字數 2669 閱讀 4791

python中xml的操作可以使用dom庫、sax庫、etree庫(這個是新的)、parsers庫。其中dom.minidom是dom輕量級模組,這裡介紹dom.minidom和etree兩個模組這裡以userinfo.xml檔案為例,xml

內容如下:

xml解析

>>>xmldoc = minidom.parse('userinfo.xml')  #it will load a xml file,can use filename or openobject

>>>xmldoc

>>>print xmldoc.toxml()  #output all xml

<?xml  version="1.0" encoding="utf-8"?>

george

john

reminder

magicdmer

don't forget the meeting!

>>>node = xmldoc.firstchild

>>>print node.toxml()

george

john

reminder

magicdmer

don't forget the meeting!

>>>print node.firstchild.toxml()   #this will display blank,because it find '\n'

>>>print node.childnodes[1].toxml()

george

>>>print node.childnodes[2].toxml()      #it is '\n', display blank

>>>print node.childnodes[3].toxml()

john

>>>print node.lastchild.toxml()      #it find zuihou element,it is '\n'

>>>

搜尋元素

>>>from xml.dom import minidom

>>>xmldoc = minidom.parse('userinfo.xml')

>>>findit = xmldoc.getelementsbytagname('name')   #it return element object

>>>print findit[0].toxml()

magicdmer

>>>print findit[0].tagname

name

訪問元素屬性

類似<ref id="bit">

>>>from xml.dom import minidom

>>>xmldoc = minidom.parse('userinfo.xml')

>>>findit = xmldoc.getelementsbytagname('ref')      #it return element object

>>>it = findit[0]>>>it.attributes.keys()

[u'id']

>>>it.attributes.values()

>>>it.attributes["id"]

>>>print it.attributes["id"].name

u'id'

>>>print it.attributes["id"].value

u'bit'

>>>from xml.etree.elementtree import elementtree

>>>tree = elementtree()

>>>tree.parse('userinfo.xml')

>>>p = tree.find('name')

>>>print p.text

magicdmer

>>>print p.tag

name

Python 操作XML檔案

1 xml 建立 1 import xml.etree.elementtree as et 23 new xml et.element personinfolist 最外面的標籤名 4 personinfo et.subelement new xml,personinfo attrib 對應的引數是...

Python操作XML檔案 XML概述

xml 可擴充套件標置語言,為html 超文字標置語言 的補充。html用於顯示資料,而xml用於傳輸和儲存資料 一.xml語法 xml檔案通常分為兩部分 檔案宣告和檔案主體 檔案宣告 位於第一行 version標明此檔案所用的標準的版本號,必須要有 encoding標明此檔案中所使用的字元型別,可...

python 寫xml檔案的操作

要生成的xml檔案格式如下 sample xml thing ma xiaoju springs widgets,inc.first i think widgets are greate.you should buy lots of them forom spirngy widgts,inc fro...