python - 编写用下划线替换 hypen 的编辑过的 xml
问题描述
因此,我试图编写一个新的 xml 文件,通过用下划线替换连字符来从原始文件中编辑,然后开始为其余代码处理该 xml 文件。
这是我的代码:
import xml.etree.ElementTree as ET
from lxml import etree
#attaching xml file
xmlfile = "hook_zap.xml"
tree = ET.parse(xmlfile)
root = tree.getroot()
#replace hypen with underscore within the xml
doc = etree.parse(xmlfile)
for e in doc.xpath('//*[contains(local-name(),"-")]'):
e.tag = e.tag.replace('-','_')
refracted = etree.tostring(doc, method='xml')
#create a new xml file with refracted file
refracted.write('base.xml')
#print (refracted)
我不断收到这个错误:
AttributeError:“字节”对象没有属性“写入”
解决方案
像任何其他类型的数据一样写入refracted
文件:
with open('base.xml', 'w') as f:
f.write(refracted.decode('utf-8'))
推荐阅读
- vue.js - Vue 或 Webpack 编译的 JS 缓存管理
- c++ - 动态数组的实现
- xml - 如何通过 xml 配置 spring security 5.4.1 以使 oauth2 注销正常工作?
- python - Jupyter / Python — 有没有办法在每个 Jupyter 单元中自动运行 %%time 之类的魔术命令?
- python - Discord.py 响应反应
- c++ - 如何限制 rand 函数可以生成的数字。(分段故障)
- python-3.x - 如何使用 pandas 在 csv 文件的最后一行和特定列中插入文本?
- internationalization - 是否有从多个 .po 文件生成所有 .mo 文件的命令?
- javascript - 为 DT 数据表上的双击事件创建 R 闪亮绑定
- python - 在 pandas 中爆炸两列:ValueError