解析和修改XML-python cookbook(第3版)高清中文完整版

时间:2021-06-10 05:19:32
【文件属性】:
文件名称:解析和修改XML-python cookbook(第3版)高清中文完整版
文件大小:4.84MB
文件格式:PDF
更新时间:2021-06-10 05:19:32
python cookbook 第3版 高清 中文完整版 6.6 解析和修改XML 问题 你想读取一个XML文档,对它 一些修改,然后将结果写回XML文档。 解决方案 使用 xml.etree.ElementTree 模块可以很容易的处理这些任务。 第一步是以通常的方式来 解析这个文档。例如,假设你有一个名为 pred.xml 的文档,类似下面这样: 下面是一个利用 ElementTree 来读取这个文档并对它做一些修改的例子: >>> from xml.etree.ElementTree import parse, Element >>> doc = parse('pred.xml') >>> root = doc.getroot() >>> root >>> # Remove a few elements >>> root.remove(root.find('sri')) >>> root.remove(root.find('cr')) >>> # Insert a new element after ... >>> root.getchildren().index(root.find('nm')) 1 >>> e = Element('spam') >>> e.text = 'This is a test' >>> root.insert(2, e) >>> # Write back to a file >>> doc.write('newpred.xml', xml_declaration=True) >>> 处理结果是一个像下面这样新的XML文件: 讨论

网友评论