阻止ElementTree.parse()在Python 2.7中序列化换行符?

时间:2018-02-07 15:35:13

标签: python xml python-2.7 elementtree

有没有人知道防止ElementTree对换行进行序列化的技巧?在这种情况下,通过在多行中分解一长串文本的内容来保持源xml文档的某种程度的人类可读性是有用的。但是,解析文件的输出应将其视为单行。

举例说明:给定一个文件,tasks.xml:

<?xml version="1.0" encoding="UTF-8"?>
<tasks>
    <task>
        <title>Work in a Button Factory</title>
        <description>Push
            the
            button
            with
            your
            left
            hand.
        </description>
    </task>
</tasks>

read.py:

import xml.etree.ElementTree as ET
root = ET.parse("tasks.xml")
print root.find('./task/title').text
print root.find('./task/description').text

目前的输出是:

work in a button factory
Push
            the
            button
            with
            your
            left
            hand.

但是希望输出应该是:

work in a button factory
Push the button with your left hand.

1 个答案:

答案 0 :(得分:0)

这是否符合您的要求?

  desc = root.find('./task/description').text
  print ' '.join(desc.split())

在内联中执行大量内容会有点难看,但您可以轻松地将其包含在函数中:

  def oneline(elementText):
      return ' '.join(elementText.split())

  print oneline(root.find('./task/description').text)