python处理xml文件的方法,供大家学习参考。
1. xml.etree.ElementTree module
两种方法去读取并解析XML文件
1)
import xml.etree.ElementTree as ET
tree = ET.parse('sample.xml')
root = tree.getroot()
2)
f = open('sample.xml','r')
xml = f.read()
root = ET.fromstring(xml)
folder_nodes = root.getiterator('FOLDER')
folder_node = folder_nodes[0]
folder_node.keys() # Show list of the Element keys
folder_node.items() # Show tuple of the Element
folder_node.attrib['NAME'] # Show value of attribute 'NAME'
folder_node.set('NAME','TEST_SET') # Set or change value for the attribute 'NAME'
将修改的东西写回xml文件
tree.write('sample.xml')
tree 是一个xml.etree.ElementTree.ElementTree instance。有如下方法:
class ElementTree
| Methods defined here:
|
| __init__(self, element=None, file=None)
|
| find(self, path)
|
| findall(self, path)
|
| findtext(self, path, default=None)
|
| getiterator(self, tag=None)
|
| getroot(self)
|
| parse(self, source, parser=None)
|
| write(self, file, encoding='us-ascii')
root, folder_node 都是一个Element, 有如下方法:
class _ElementInterface
| Methods defined here:
|
| __delitem__(self, index)
|
| __delslice__(self, start, stop)
|
| __getitem__(self, index)
|
| __getslice__(self, start, stop)
|
| __init__(self, tag, attrib)
|
| __len__(self)
|
| __repr__(self)
|
| __setitem__(self, index, element)
|
| __setslice__(self, start, stop, elements)
|
| append(self, element)
|
| clear(self)
|
| find(self, path)
|
| findall(self, path)
|
| findtext(self, path, default=None)
|
| get(self, key, default=None)
|
| getchildren(self)
|
| getiterator(self, tag=None)
|
| insert(self, index, element)
|
| items(self)
|
| keys(self)
|
| makeelement(self, tag, attrib)
|
| remove(self, element)
|
| set(self, key, value)
2. xml.dom.minidom module