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

2024-01-11

我的 python (2.7) 脚本使用以下命令输出以下 XMLlxml图书馆:

<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" />

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

使用生成 xml 后lxml库,我处理输出。 以下代码仅经过测试可以使用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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 lxml 将长 XML 标签拆分为多行 的相关文章

随机推荐