2016-08-01 72 views
0

我想在python中複製一些XML代碼以將其放入我目前正在處理的程序中,該程序會執行一些全景捕獲。最後,想法是導出捕獲細節的XML文件,以便更容易地導入各種全景捕獲程序之一。python查詢中的xml子元素

我對Python相當新,但一直在使用xml.etree.ElementTree,與此我可以設置信息,如根聲明和標題和子標題,但我有點失去了兩點,第一個是如何通過一個子元素,我可以設置一個值(如GPS),第二個是如何一個子元素可以有多個值(例如馬賽克/重疊最小值)。

對於我有以下工作的元素;

root = etree.Element("papywizard") 
root.set("version", "c") 
header = etree.SubElement(root,"header") 
general = etree.SubElement(header, "general") 
title = etree.SubElement(general,"title") 

我當時以爲我可以做這樣的事情title.text("Test123")但這並沒有工作。我正在嘗試複製的完整XML如下,是否有人能夠指引我如何在子元素標記中設置文本,以及除了可以將多少個標記聚合爲一個子元素?

非常感謝!

<?xml version="1.0" encoding="utf-8"?> 
<papywizard version="c"> 
    <header> 
     <general> 
      <title> 
       Test Capture 1 
      </title> 
      <gps> 
       37.8022697,-122.4056749 
      </gps> 
      <comment> 
       Add your comments here 
      </comment> 
     </general> 
     <shooting mode="mosaic"> 
      <headOrientation> 
       up 
      </headOrientation> 
      <cameraOrientation> 
       landscape 
      </cameraOrientation> 
      <stabilizationDelay> 
       5.0 
      </stabilizationDelay> 
      <counter> 
       001 
      </counter> 
      <startTime> 
       2014-02-23_13h59m01s 
      </startTime> 
      <endTime> 
       2014-02-23_13h53m33s 
      </endTime> 
     </shooting> 
     <camera> 
      <timeValue> 
       5.0 
      </timeValue> 
      <bracketing nbPicts="1"/> 
      <sensor coef ="4.74" ratio="4:3"/> 
     </camera> 
     <lens type="rectilinear"> 
      <focal> 
       12.7 
      </focal> 
     </lens> 
     <mosaic> 
      <nbPicts pitch="5" yaw="10"/> 
      <overlap minimum="0.25" pitch="0.25" yaw="0.25"/> 
     </mosaic> 
    </header> 
    <shoot> 
     <pict bracket="1" id="1"> 
      <time> 
       2014-02-23_13h59m01s 
      </time> 
      <position pitch="37.96" roll="0.0" yaw="-99.96"/> 
     </pict> 
     <pict bracket="1" id="2"> 
      <time> 
       2014-02-23_13h59m01s 
      </time> 
      <position pitch="18.98" roll="0.0" yaw="-99.96"/> 
     </pict> 
     <pict bracket="1" id="3"> 
      <time> 
       2014-02-23_13h59m01s 
      </time> 
      <position pitch="0.00" roll="0.0" yaw="-99.96"/> 
     </pict> 
    </shoot> 
</papywizard> 

回答

2
import xml.etree.ElementTree as ET 

root = ET.Element("papywizard") 
root.set("version", "c") 
header = ET.SubElement(root,"header") 
general = ET.SubElement(header, "general") 
title = ET.SubElement(general,"title") 
title.text = str('Test123') # This is how you set it 

tree = ET.ElementTree(root) # This step will form a tree 
tree.write('expected.xml') # This step will save the xml file. 
1

您必須使用以下命令:

title.text = "some text" 
1

文本節點和元素節點兩種節點和XML元素節點可以在任何任意數量的文本和/或元素的子節點訂購。

如果你想添加文本節點,你可以用.text屬性做

title.text = "Sometext" 

如果你想添加的屬性,你可以用set命令

title.set('Attribute name', 'Attributevalue') 
+0

感謝所有人的幫助,每個答案完美無缺:)。非常感謝! – user1829564