2015-12-11 38 views
1

我想將一些子元素添加到xml樹的父元素中。 源XML是:使用lxml將多個元素添加到xml

<catalog> 
    <element> 
     <collection_list /> 
    </element> 
    <element> 
     <collection_list /> 
    </element> 
</catalog> 

我試過下面的代碼在Python 3:

from lxml import etree 
tree = etree.parse('source.xml') 
root = tree.getroot() 

elementCollections = tree.xpath('/catalog/element/collection_list') 

for element in elementCollections: 
    childElement = etree.SubElement(element, "collection") 
    listOfElementCollections = ['c1', 'c2', 'c3'] 

    for elementCollection in listOfElementCollections: 
     childElement.text = elementCollection 

newtree = etree.tostring(tree, encoding='utf-8') 
newtree = newtree.decode("utf-8") 
print(newtree) 

但不是:

<catalog> 
    <element> 
     <collection_list> 
      <collection>c1</collection> 
      <collection>c2</collection> 
      <collection>c3</collection> 
     </collection_list> 
    </element> 
    <element> 
     <collection_list> 
      <collection>c1</collection> 
      <collection>c2</collection> 
      <collection>c3</collection> 
     </collection_list> 
    </element> 
</catalog> 

我有這樣的結果:

<catalog> 
    <element> 
     <collection_list> 
      <collection>c3</collection> 
     </collection_list> 
    </element> 
    <element> 
     <collection_list> 
      <collection>c3</collection> 
     </collection_list> 
    </element> 
</catalog> 

請解釋一下h ow在樹中插入多個元素。編輯: 「childElement」的標籤的固定名稱

回答

1

您需要添加集合在內部for循環,而不是外:

for element in elementCollections: 
    listOfElementCollections = ['c1', 'c2', 'c3'] 

    for elementCollection in listOfElementCollections: 
     childElement = etree.SubElement(element, "collection") 
     childElement.text = elementCollection 

newtree = etree.tostring(root, encoding='utf-8') 
newtree = newtree.decode("utf-8") 
print newtree 
0

使用此代碼:

from lxml import etree 
tree = etree.parse('source.xml') 
root = tree.getroot() 

elementCollections = tree.xpath('/catalog/element/collection_list') 

for element in elementCollections: 
    childElement = etree.SubElement(element, "collectionName") 
    listOfElementCollections = ['c1', 'c2', 'c3'] 

    for elementCollection in listOfElementCollections: 
     childElement2 = etree.SubElement(childElement, "collection") 
     childElement2.text = elementCollection 

newtree = etree.tostring(tree, encoding='utf-8') 
newtree = newtree.decode("utf-8") 
print(newtree) 

您需要在循環創建新的元素。

+0

感謝您的幫助,阿里!你是對的。注意:我已經修復了childElement標籤的錯誤,所以你可以在8行代碼中修復它 – nycmoma