我的 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/