2016-08-03 2 views
0

고정 섹션의 기존 파일에 삽입하려는 특정 데이터 세트로 작업하고 있습니다. 나는이처럼 보이는에서 XML 파일을 변경하려면 :Python을 사용하여 XML 파일에 데이터 삽입

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

같이하기 :

<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

고맙습니다. 나는 대답에 가까이 있지만 시가는 어디에서 가깝습니까? 고맙습니다!!!. –

관련 문제