2016-08-20 7 views
0

私はこの問題を解決するために探しています。 xmlファイルに書き込もうとすると、同じことが2回書き込まれます。Xmlは同じことを二度書く

それはコードです:

def writeIntoXml(fileName, tagElement, textElement): 
    tree = ET.ElementTree(file = fileName) 
    root = tree.getroot() 
    newElement = ET.SubElement(root, tagElement) 
    newElement.text =textElement; 
    newElement.tail ="\n" 
    root.append(newElement) 
    tree.write(fileName, encoding='utf-8') 

私はこのタグを使用して、このXMLファイルを、持っている場合、私は新しいタグ(ES「質問-3」例3「/質問-3」)を書いた場合、私が手問題

書き込まれる前に、XMLFILE:書かれた後

<Questions> 
    <Question-1>Example1</Question-1> 
    <Question-2>Example2</Question-2> 
</Questions> 

がXMLFILE:

<Questions> 
    <Question-1>Example1</Question-1> 
    <Question-2>Example2</Question-2> 
    <Question-3>Example3</Question-3> 
    <Question-3>Example3</Question-3> 
</Questions> 

文法上の申し訳ありません。

+0

あなたは、以下の正しい答えを持っているので、承認されたとして、それをマークしてくださいを使用する必要があります。他のユーザーがあなたの質問に注意を払わないように助けます。 –

答えて

1

ET.SubElement()は、要素を自動的に付加することに注意してください。最初にSubElement()、次にappend()に要素を2回追加します。

あなたはどちらかだけの

newElement = ET.SubElement(root, tagElement) 
newElement.text = textElement; 
newElement.tail = "\n" 

または

newElement = ET.Element(tagElement) 
newElement.text = textElement; 
newElement.tail = "\n" 
root.append(newElement) 
+0

くそー、ありがとう^^私はそれを修正します。それはとても簡単だった –

関連する問題