使用lxml在多行中拆分长XML标记 [英] Split long XML tags in multiple lines with lxml
本文介绍了使用lxml在多行中拆分长XML标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的python(2.7)脚本正在使用lxml
库输出以下XML:
My python (2.7) script is outputting the following XML using lxml
library:
<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"/>
我想将其输出为多行,每个属性输出一行:
I would like to output it in multiple lines, one per attribute:
<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" />
推荐答案
我想出了一种非常幼稚且效率低下的方法.
I came up with a very naive and inefficient approach.
使用lxml
库生成xml之后,我将处理输出.
以下代码仅经过测试,可与lxml
输出配合使用,并假定我们每行都有一个标记.
After generating the xml using lxml
library, I process the output.
The following code is only tested to work with lxml
output and assumes we have a tag per line.
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
尽管这可以完成工作,但这远非最佳方法. 我想知道是否有更好,更简单的方法.
Although this gets the job done, it is far from being an optimal approach. I wonder if there's a better and simpler way of doing this.
这篇关于使用lxml在多行中拆分长XML标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文