使用lxml将输出格式化为XML

JAW*_*AWE 6 python xml lxml pretty-print python-3.x

我的程序基本上读取了一个输入文件,从该文件生成一个lxml.etree,而不是例如我向etree添加一个节点,然后我想将它打印回一个文件.所以要把它写回我使用的文件:

et.write('Documents\Write.xml', pretty_print=True)
Run Code Online (Sandbox Code Playgroud)

我的输出是:

<Variable Name="one" RefID="two"><Component Type="three"><Value>four</Value></Component></Variable>
Run Code Online (Sandbox Code Playgroud)

虽然我喜欢这样的东西:

<Variable Name="one" RefID="two">
    <Component Type="three">
        <Value>four</Value>
    </Component> 
</Variable>
Run Code Online (Sandbox Code Playgroud)

我哪里弄错了?我尝试了很多解决方案,但似乎没有工作(beautifulsoup,整洁,解析器...)

Ski*_*ect 0

这很奇怪,因为这正是它应该工作的方式。你能试试这个吗:

root = etree.XML( YOUR XML STRING )
print etree.tostring(root, pretty_print=True)

<Variable Name="one" RefID="two">
  <Component Type="three">
    <Value>four</Value>
  </Component>
</Variable>
Run Code Online (Sandbox Code Playgroud)

这应该会生成一个格式化的字符串,您可以自己处理该字符串。

  • 感谢您的回答,但这就是我的做法。以这种方式它可以工作,但是当我在文件上写入时却不能......我不知道为什么!不管怎么说,还是要谢谢你。 (2认同)