【发布时间】:2013-07-17 01:33:30
【问题描述】:
我的程序基本上是读取一个输入文件,从该文件生成一个 lxml.etree,而不是例如我向 etree 添加一个节点,然后我想将它打印回文件上。 因此,要将其写回我使用的文件中:
et.write('Documents\Write.xml', pretty_print=True)
我的输出是:
<Variable Name="one" RefID="two"><Component Type="three"><Value>four</Value></Component></Variable>
虽然我想要类似的东西:
<Variable Name="one" RefID="two">
<Component Type="three">
<Value>four</Value>
</Component>
</Variable>
我错在哪里?我尝试了很多解决方案,但似乎都没有效果(beautifulsoup、tidy、parser...)
【问题讨论】:
-
会不会是windows相关的?如果您尝试使用
io模块打开输出文件:fp=io.open('Documents\Write.xml', 'w', newline='\r\n') and thenwrite tofplike thatet.write(fp, pretty_print=True)(参见 docs.python.org/2/library/io.html#io.open) -
嗨,保罗,我正在尝试您所说的,但 fp 是什么?我要写的文件?对不起,我是初学者!
-
只是一个文件指针,代表你要写入的文件,是的。
et.write()可以将文件名或打开的文件指针作为输入,例如来自io.open(lxml.de/api/lxml.etree._ElementTree-class.html#write) 的内容。你可以试试import io然后et.write(io.open('Documents\Write.xml', 'w', newline='\r\n'), pretty_print=True) -
好的,我已经这样做了,我得到了这个错误:TypeError: must be unicode, not str...我该怎么办?
-
堆栈跟踪是什么? TypeError 消息之前有哪些行?
标签: python xml python-3.x lxml pretty-print