2013-11-26 88 views
0

我使用xml.etree.ElementTree解析下面的XML文件Python代碼的深度基於父標籤屬性值插入XML標籤

<main> 
    <stream id="1" name="some"> 
     <inner id="500"> 
       <sub-inner> 
       <inside> 500 </inside> 
       </sub-inner> 
     </inner> 
    </stream> 
    <stream id="2" name="some"> 
     <inner id="500"> 
       <sub-inner> 
       <inside> 500 </inside> 
       </sub-inner> 
     </inner> 
    </stream> 
</main> 

如何插入<外> 200 </outer>元素進入<子內部>標記其中< stream id =「2」one?

回答

0

試用Python lxml包裝。 :因爲lxml支持xpath來在xml上觸發查詢。

from lxml import etree 

tree = etree.parse("C:\\abc.xml") 
root = tree.getroot() 
elem = tree.xpath("//stream[@id='2']//sub-inner")[0] 
elem.append(etree.Element("outer")) 
elem1 = tree.xpath("//stream[@id='2']//sub-inner//outer")[0] 
elem1.text = "200" 

它會在哪裏sub-inner追加stream id="2"新元素outer

輸出將是:

<main> 
    <stream id="1" name="some"> 
     <inner id="500"> 
       <sub-inner> 
       <inside> 500 </inside> 
       </sub-inner> 
     </inner> 
    </stream> 
    <stream id="2" name="some"> 
     <inner id="500"> 
       <sub-inner> 
       <inside> 500 </inside> 
       <outer>200</outer> 
       </sub-inner> 
     </inner> 
    </stream> 
</main>