python - 使用 lxml 将长 XML 标签拆分为多行

标签 python xml lxml pretty-print

我的 python (2.7) 脚本使用 lxml 库输出以下 XML:

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="17dp" android:layout_marginTop="16dp" android:text="Button"/>

我想将其分多行输出,每个属性一行:

<Button
  android:id="@+id/button1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginLeft="17dp"
  android:layout_marginTop="16dp"
  android:text="Button" />

最佳答案

我想出了一个非常幼稚且低效的方法。

使用 lxml 库生成 xml 后,我处理输出。 以下代码仅经过测试,可与 lxml 输出配合使用,并假设我们每行都有一个标记。

output = etree.tostring(
    tree,
    xml_declaration=True,
    pretty_print=True,
    encoding=tree.docinfo.encoding,
)
output = output.replace("\" ","\"\n")
with open(filename, "w") as f:
    parent_tag_line = None
    for i, line in enumerate(output.splitlines()):
        line_stripped = line.lstrip(" ")
        line_ident = len(line) - len(line_stripped)
        if parent_tag_line is not None:
            if line_ident == 0 and line[:2] != "</":
                line = (parent_line_ident+2)*" " + line
            else:
                parent_tag_line = line
                parent_line_ident = line_ident
                line_stripped = line.lstrip()
                if line_stripped[:4] != "<!--" and line_stripped[:2] != "</":
                    line="\n"+line
        else:
            parent_tag_line = line
            parent_line_ident = line_ident
        print >>f, line

虽然这可以完成工作,但它远不是最佳方法。 我想知道是否有更好、更简单的方法来做到这一点。

关于python - 使用 lxml 将长 XML 标签拆分为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40410923/

相关文章:

python xpath 表的一些但不是所有列

python - PyDev:运行代码到交互式控制台

Python从命名管道获取数据

python - JSON 验证,使 schema 中定义的所有键都成为必需

javascript - 异步 xml 请求不返回

android - 如何让 float 按钮停留在布局底部?

python - 如何遍历lxml对象的节点来查看属性是否存在?

python - 获取错误 : jinja2. exception.TemplateAssertionError:没有名为 'basename' 的过滤器

xml - Jmeter - 生成 xml

html - 获取网站名称包含python 27中的HTML代码