2016-11-03 91 views
0

我的Python(2.7)脚本输出使用lxml库中的以下XML:拆分的长XML标签与LXML

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

您必须找到lxml使用的变压器串行器实现的文档,并确定它是否有任何可以控制此变量的参数。我非常怀疑它。 –

+0

感谢@JimGarrison的建议。我查阅了lxml文档,但找不到任何关于此的信息。我可以很容易地在标签之后操作字符串,但是我无法控制属性之后的字符串。我也在源代码中查找,以检查是否可以在'write()'函数中自定义'method'参数,但是我从中得不到任何东西。 –

回答

0

我想出了一个非常天真低效的方法。

使用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 

虽然这能够完成任务,这是远远的最佳手段。 我想知道是否有更好更简单的方法来做到这一点。