Python—当存在同名的多个元素属性时,如何编辑特定的XML元素内容?

Python—当存在同名的多个元素属性时,如何编辑特定的XML元素内容?,python,xml,python-2.7,elementtree,Python,Xml,Python 2.7,Elementtree,我一直在尝试在包含多个同名元素内容的XML中编辑一个特定的元素内容,但是设置元素属性所需的“for循环”将始终贯穿整个部分并全部更改 假设这是我的XML: <SectionA> <element_content attribute="device_1" type="parameter_1" /> <element_content attribute="device_2" type="parameter_2" /> </SectionA&g

我一直在尝试在包含多个同名元素内容的XML中编辑一个特定的元素内容,但是设置元素属性所需的“for循环”将始终贯穿整个部分并全部更改

假设这是我的XML:

<SectionA>
    <element_content attribute="device_1" type="parameter_1" />
    <element_content attribute="device_2" type="parameter_2" />
</SectionA>
如何访问特定元素内容并仅更改该内容

请记住,我不知道元素内容部分中当前存在的属性,因为我正在动态地将它们添加到用户的请求中

编辑: 由于@leovp,我能够解决我的问题,并提出了以下解决方案:

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

last_element.set(attribute, attribute_value)
这会导致for循环始终更改特定嵌套中的最后一个属性。 由于我正在动态添加和编辑行,因此它会更改我添加的最后一行


谢谢。

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

>>> 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>
更新:因为所讨论的XML数据事先不知道。 您可以像这样查询第一个、第二个、…、最后一个元素(索引从1开始):

但由于您仍在迭代元素,最简单的解决方案是只检查当前元素的属性:

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

嘿,非常感谢你的回答!不幸的是,我无法以这种方式搜索,因为我无法判断属性的值是什么。XML文件对我来说是“不可见的”,我应该能够动态地编辑它。如果我想更改第1/2个元素内容,是否无法检查元素内容[0]或类似的内容?我用两个可能的解决方案更新了答案。您提供的for循环没有帮助,因为正如我所说,我无法确定元素内部的属性。不过,我最终还是使用了解决方案的一部分,主要是[last()]部分,解决了这个问题。我已经更新了我原来的帖子。非常感谢您的帮助!
d2 = tree.find('element_content[@attribute="device_2"]')
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)