java中的接口是类吗
364
2022-08-27
Python从门到精通(五):文件处理-04-xml文件处理(python写入xml文件的方法)
python处理专用的领域一般都会有专门的库(类似java的三方开源包),在本节中我们使用的是xml库,也可以选用lxml库。
一、简单实现
from xml.etree.ElementTree import parsedoc = parse('test.xml')# Extract and output tags of interestfor item in doc.iterfind('pre'): pt = item.findtext('pt') fd = item.findtext('fd') v = item.findtext('v') print(f'the value of pt: {pt}') print(f'the value of fd: {fd}') print(f'the value of v: {v}')print(f'doc content: {doc}')e = doc.find('pre')print(f'e is: {e}')print(f'e tag is: {e.tag}')print(f'e text value: {e.text}')print(f"e get attribute v is: {e.get('v')}")
the value of pt: 5 MINthe value of fd: Howardthe value of v: 1378the value of pt: 15 MINthe value of fd: Howardthe value of v: 1867doc content:
二、XML解析
author is: David Beazleycontent is: 三、XML修改 from xml.etree.ElementTree import parse, Elementdoc = parse('test.xml')root = doc.getroot()print(f'root is: {root}')root.remove(root.find('sri'))root.remove(root.find('cr'))print(f"root children index: {root.getchildren().index(root.find('nm'))}")e = Element('spam')e.text = 'This is a test'root.insert(2, e)print(f"doc write: {doc.write('newpred.xml', xml_declaration=True)}") 四、DICT与XML from xml.etree.ElementTree import Elementdef dict_to_xml(tag, d): element = Element(tag) for key, val in d.items(): child = Element(key) child.text = str(val) element.append(child) return elementcourse_dict = {'course_name': 'python', 'total_class': 30, 'score':0.3}elem = dict_to_xml('course', course_dict)print(f'elem is: {elem}')from xml.etree.ElementTree import tostringprint(f'elem to sting is: {tostring(elem)}')elem.set('_id','1234')print(f'elem to sting is: {tostring(elem)}')#只能创建字符串类型的值def dict_to_xml_str(tag, d): part_list = [f'<{tag}>'] for key, val in d.items(): part_list.append(f'<{key}>{val}{key}>') part_list.append(f'{tag}>') return ''.join(part_list)d = {'courese_name': ' elem is:
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~