我使用的是特定的数据集,我希望将这些数据插入到固定节中的现有文件中。我想将XML文件改成这样:
<SBEDataUploadFile>
<ApplicationData>
<firmware>
<SoftwareVersion>1.0</SoftwareVersion>
<BuildDate>Dec 1 2012 10:43:42</BuildDate>
</firmware>
</ApplicationData>
</SBEDataUploadFile>
看起来像这样:
^{pr2}$我用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
。只需在根元素上设置文本节点:相关问题 更多 >
编程相关推荐