【问题标题】:Formatting the output as XML with lxml使用 lxml 将输出格式化为 XML
【发布时间】: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 to fp like that et.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


【解决方案1】:

不要使用标准解析器。 使用带有remove_blank_text=True 的自定义解析器。

parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(self.output_file, parser=parser)
# Do stuff with the tree here
tree.write(your_output_file, pretty_print=True)

【讨论】:

【解决方案2】:

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

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>

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

【讨论】:

  • 感谢您的回答,但我就是这样做的。以这种方式它可以工作,但是当我在文件上写入时它不会..我不知道为什么!还是谢谢。
  • 我也在这样做,但遇到了与@JAWE相同的问题
猜你喜欢
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-15
  • 2023-01-28
相关资源
最近更新 更多