使用python读取GB2312编码的xml文件
读取utf-8编码
from xml.tree import ElemenTree
tree = ElementTree.parse(file_path)
读取GB2312编码
from xml.tree import ElemenTree
tree = ElementTree.parse(file_path, parser=ElementTree.XMLParser(encoding='utf-8'))
新建一个XML并写入内容
def create_xml(xml_path):
doc = xml.dom.minidom.Document()
root = doc.createElement('root')#新建根节点
doc.appendChild(root)
airCount = doc.createElement("airCount")
airCount.appendChild(doc.createTextNode('设置节点内容'))
root.appendChild(airCount)#设置为根节点的子节点
fp = open(xml_path, 'w')
#写入xml文件并设置xml文件编码
doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding='utf-8')
fp.close()
增加一个节点(GB2312编码)
def insert_node(xml_path):
#GB2312编码xml文件读取方式
doc_tree = xTree.parse(xml_path, parser=xTree.XMLParser(encoding='utf-8'))
root = doc_tree.getroot()
count = xTree.Element('airCount')
count.text = str('设置节点内容')
root.append(count)
#记得指定编码方式,否则就不是GB2312编码了
doc_tree.write(xml_path, encoding="GB2312")
增加一个节点(其他编码,如utf-8)
def insert_node(xml_path):
doc_tree = xTree.parse(xml_path)
root = doc_tree.getroot()
count = xTree.Element('airCount')
count.text = str('设置节点内容')
root.append(count)
#指定编码方式
doc_tree.write(xml_path, encoding="utf-8")