2016-10-13 9 views
0

私はXMLファイルを読みやすくするためにPrettifyを使用しています。私はexciling XMLファイルにいくつかの新しい情報を追加していますが、ファイルに保存すると、行間に余分な行があります。これらの行を削除する方法はありますか?以下は、私は以下XMLで余分な行を追加することをお勧めします

import xml.etree.ElementTree as xml 
import xml.dom.minidom as minidom 
from lxml import etree 

def prettify(elem): 
    rough_string = xml.tostring(elem, 'utf-8') 
    reparsed = minidom.parseString(rough_string) 
    return reparsed.toprettyxml(indent="\t") 


cid = "[123,123,123,123,123]" 

doc = xml.parse('test.xml') 
root = doc.getroot() 

root.getchildren().index(root.find('card')) 

e = xml.Element('card') 
e.set('id', cid) 
n = xml.SubElement(e, "name") 
n.text = "FOLDER" 
r = xml.SubElement(e, "red") 
r.text = "FILE.AVI" 
g = xml.SubElement(e, "green") 
g.text = "FILE.AVI" 
b = xml.SubElement(e, "blue") 
b.text = "FILE.AVI" 

root.insert(0, e) 

doc2 = prettify(root) 

with open("testnew.xml", "w") as f: 
    f.write(doc2) 

を使用しているコードは、私がファイルに

<data> 


    <card id="[123,123,123,123,123]"> 
      <name>FOLDER</name> 
      <red>FILE.AVI</red> 
      <green>FILE.AVI</green> 
      <blue>FILE.AVI</blue> 
    </card> 
    <card id="[000,000,000,000,000]"> 


      <name>Colours</name> 


      <red>/media/usb/cow.avi</red> 


      <green>/media/usb/pig.avi</green> 


      <blue>/media/usb/cat.avi</blue> 


    </card> 


</data> 

入力ファイル「のtest.xml」は

<data> 
    <card id="[000,000,000,000,000]"> 
     <name>Colours</name> 
     <red>/media/usb/cow.avi</red> 
     <green>/media/usb/pig.avi</green> 
     <blue>/media/usb/cat.avi</blue> 
    </card> 
</data> 
+0

何の入力は次のようになりTEST.XMLのでしょうか? – barny

+0

@barny上記の入力XMLを参照してください – LeeEng

答えて

0

追加された新しいコンテンツのように見える得るものです印刷されています。既存のテキストが問題

doc2 = prettify(root) 

関連答えを呼び出す前に

for elem in root.iter('*'): 
    if elem == e: 
     print "Added XML node does not need to be stripped" 
     continue 
    if elem.text is not None: 
     elem.text = elem.text.strip() 
    if elem.tail is not None: 
     elem.tail = elem.tail.strip() 

を追加解決のいずれかの "prettification" を削除:Python how to strip white-spaces from xml text nodes

+0

ありがとうございます。パーフェクトです – LeeEng

関連する問題