2016-11-03 5 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"/> 

私は、複数行で出力をする属性ごとに1つずつたいと思います:

<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出力でのみ動作することがテストされており、1行にタグがあるものとします。

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 

これはジョブを実行しますが、最適なアプローチではありません。 これを行うためのより簡単で簡単な方法があるのだろうかと思います。

関連する問題