2017-03-21 29 views
2

我一直在試圖編輯XML中的一個特定的元素內容,其中包含多個相同名稱的元素內容,但設置元素屬性所需的「for循環」將始終貫穿整個部分並更改它們所有。Python - 如何在存在多個同名元素屬性時編輯特定的XML元素內容?

讓我們說,這是我的XML:

<SectionA> 
    <element_content attribute="device_1" type="parameter_1" /> 
    <element_content attribute="device_2" type="parameter_2" /> 
</SectionA> 
我目前使用的ElementTree使用此代碼時某部分具有不同的名稱元素含量的作品完美

,但它並沒有這樣的情況下工作 - 名稱相同。它將簡單地將所有內容的屬性更改爲具有相同的值。

for element in root.iter(section): 
    print element 
    element.set(attribute, attribute_value) 

如何訪問特定元素內容並僅更改該內容?

請記住,我不知道element_content部分中當前存在的屬性,因爲我將它們動態添加到用戶的請求中。

編輯: 感謝@leovp我能解決我的問題,並用此溶液想出了:

for step in root.findall(section): 
    last_element = step.find(element_content+'[last()]') 

last_element.set(attribute, attribute_value) 

這將導致在for循環總是在發生變化的具體鳥巢最後一個屬性。 由於我動態添加和編輯線條,這使得它改變了我添加的最後一個。

謝謝。

回答

2

您可以使用有限的XPath支持,xml.etree提供:

>>> from xml.etree import ElementTree 
>>> xml_data = """ 
... <SectionA> 
...  <element_content attribute="device_1" type="parameter_1" /> 
...  <element_content attribute="device_2" type="parameter_2" /> 
... </SectionA> 
... """.strip() 
>>> tree = ElementTree.fromstring(xml_data) 
>>> d2 = tree.find('element_content[@attribute="device_2"]') 
>>> d2.set('type', 'new_type') 
>>> print(ElementTree.tostring(tree).decode('utf-8')) 
<SectionA> 
    <element_content attribute="device_1" type="parameter_1" /> 
    <element_content attribute="device_2" type="new_type" /> 
</SectionA> 

這裏最重要的部分是一個XPath表達式,在這裏我們用它的名字查找元素和屬性值:

d2 = tree.find('element_content[@attribute="device_2"]') 

更新:因爲有問題的XML數據事先不知道。 您可以查詢第一,第二,......,最後是這樣的元素(索引從1開始):

tree.find('element_content[1]') 
tree.find('element_content[2]') 
tree.find('element_content[last()]') 

但是既然你遍歷元素,無論如何,最簡單的辦法是隻檢查當前元素的屬性:

for element in root.iter(section): 
    if element.attrib.get('type') == 'parameter_2'): 
     element.set(attribute, attribute_value) 
+0

嘿,非常感謝您的回答!不幸的是,我無法以這種方式進行搜索,因爲我無法確定屬性的值。 XML文件對我來說是「不可見的」,我應該可以動態編輯它。如果我想要更改1st/2nd element_conent,是否沒有辦法檢查element_content [0]或類似的東西? –

+0

我用一些可能的解決方案更新了答案。 – leovp

+0

您提供的for循環沒有幫助,因爲正如我所說的,我無法確定位於元素內部的屬性。然而,我確實使用了部分解決方案,主要是[last()]部分。我已經更新了原來的帖子。非常感謝你的協助! –

相關問題