2016-08-03 12 views
0

固定セクションの既存のファイルに挿入する特定のデータセットを扱っています。このように見えるようにPythonでXMLファイルにデータを挿入する

<SBEDataUploadFile> 
    <ApplicationData> 
     <firmware> 
     <SoftwareVersion>1.0</SoftwareVersion> 
     <BuildDate>Dec 1 2012 10:43:42</BuildDate> 
     </firmware> 
     </ApplicationData> 
</SBEDataUploadFile> 

:私はこのように見ているから、XMLファイルを変更したい

<SBEDataUploadFile> 
<![CDATA[ 
** Location 001 
** Latitude In 18.33885 
** Longitude In 64.97647 
** Time In 11:55 
** Depth (ft) 10 
** Line Out (ft) 5 
** Time Out 11:56 
** Latitude Out 18.33885 
** Longitude Out 64.97647 
** Notes 
]]> 
    <ApplicationData> 
     <firmware> 
     <SoftwareVersion>1.0</SoftwareVersion> 
     <BuildDate>Dec 1 2012 10:43:42</BuildDate> 
     </firmware> 
     </ApplicationData> 
    </SBEDataUploadFile> 

私はxml.etree.ElementTreeでこれを試してみましたが、私の結果は、それが後に下にコメントを追加するということです</ApplicantionData>。ここに私の現在のコードは次のとおりです。

import xml.etree.ElementTree as ET 

#variables 
location = "BPT" 
latitude_in = 0 
longitude_in = 0 
time_in = 0 
depth = 0 
line_out = 0 
time_out = 0 
latitude_out = 0 
longitude_out = 0 
notes = "" 

#formatting and converting all variables to string 
toString = "<![CDATA["+"\n"+"** Location "+location+"\n"+"** Latitude In "\ 
+str(latitude_in)+"\n"+"** Longitude In "+str(longitude_in)+"\n"+\ 
"** Time In "+str(time_in)+"\n"+"** Depth (ft) "+str(depth)+"\n"+"** Line Out (ft) "\ 
+str(line_out)+"\n"+"** Time Out "+str(time_out)+"\n"+"** Latitude Out "\ 
+str(latitude_out)+"\n"+"** Longitude Out "+str(longitude_out)+"\n"+"** Notes "+notes+"\n"+"]]>" 

xml_filepath = xmlfilepath.xml 
xml_tree = ET.parse(xml_filepath) 
xml_root = xml_tree.getroot() 
ET.SubElement(xml_root, toString) 

print ET.tostring(xml_root) 

、これらは私の現在の結果である:

<SBEDataUploadFile> 
    <ApplicationData> 
     <firmware> 
     <SoftwareVersion>1.0</SoftwareVersion> 
     <BuildDate>Dec 1 2012 10:43:42</BuildDate> 
     </firmware> 
     </ApplicationData> 
    <<![CDATA[ 
** Location BPT 
** Latitude In 0 
** Longitude In 0 
** Time In 0 
** Depth (ft) 0 
** Line Out (ft) 0 
** Time Out 0 
** Latitude Out 0 
** Longitude Out 0 
** Notes 
]]> /></SBEDataUploadFile> 

私は、これはそれが私の望む結果のように見えるようにすることができるようにしたいとする前に、余分な/>権利を取り除きます</SBEDataUploadFile>

答えて

0

SubElementは必要ありません。ルート要素にテキストノードを設定するだけです。

xml_root.text = toString 
+0

ありがとうございました!!!私は、私が答えに近いものの、葉巻はありません。ありがとうございました!!!。 –

関連する問題