使用 python 将数据插入 XML 文件

Inserting data into XML file with 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>.

之前去掉多余的 />

您不需要 SubElement。只需在根元素上设置文本节点:

xml_root.text = toString