2016-11-03 87 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 

雖然這能夠完成任務,這是遠遠的最佳手段。 我想知道是否有更好更簡單的方法來做到這一點。