首页 > 解决方案 > 编写用下划线替换 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:“字节”对象没有属性“写入”

标签: pythonxmlelementtreewrite

解决方案


像任何其他类型的数据一样写入refracted文件:

with open('base.xml', 'w') as f:
    f.write(refracted.decode('utf-8'))

推荐阅读