我有一个xml文件,如下所示:
<sample>
<attributes> xyz
</attributes>
</sample>
我想添加到xml的开头:
<!DOCTYPE sample SYSTEM "location/sample.dtd">
我只能使用python 2.5。所以,任何人都可以建议我怎么能有这个。我想最终的xml文件是:
<sample>
<!DOCTYPE sample SYSTEM "location/sample.dtd">
<attributes> xyz
</attributes>
</sample>
答案 0 :(得分:0)
作为先前答案的概括:
fp = open(xml_filepath, 'r')
content = fp.readlines()
fp.close()
final_content = content[:1]
final_content.append('<!DOCTYPE sample SYSTEM "location/sample.dtd">')
final_content.extend(content[1:])
fp = open(xml_filepath, 'w')
fp.writelines(final_content)
fp.close()
答案 1 :(得分:-1)
以下代码将在python脚本的当前目录中编写和/或覆盖file.xml。如果您想将file.xml写入某个目录,请告诉我。
from __future__ import with_statement
with open('file.xml', 'w') as file:
file.write(r'''
<sample>
<!DOCTYPE sample SYSTEM "location/sample.dtd">
<attributes> xyz
</attributes>
</sample>''')