如何使用 Python 编写新字段文本 XML 属性?

Hw to write a new field text XML attribute using Python?

我有一个 XML 这样的:

<process>
     <NAME source="hsfg" class="hshah" property="Name">
          <VALUE type="string"></VALUE>
          <VALUE type="None"></VALUE>
     </NAME>
     <number source="fdsg" class="hgdgf" property="gagfa">
          <VALUE type="string"></VALUE>
          <VALUE type="None"></VALUE>
     </number>
     <id source="ag" class="gfdg" property="fadg">
          <VALUE type="string"></VALUE>
          <VALUE type="None"></VALUE>
     </id>
</process>

我想在此处添加文字 <VALUE type="string"></VALUE> 我在这里试过,但它不仅在这个 <NAME source="hsfg" class="hshah" property="Name">

属性中增加了所有 VALUE
import xml.etree.ElementTree as ET

tree = ET.parse('Example.xml')
root = tree.getroot()

for elem in tree.iter('VALUE'):
    elem.text = 'new value'

tree = ET.ElementTree(root)
tree.write('newitems.xml')

我的期望输出是这样的:

<process>
     <NAME source="hsfg" class="hshah" property="Name">
          <VALUE type="string">new value</VALUE>
          <VALUE type="None"></VALUE>
     </NAME>
     <number source="hsfg" class="hgdgf" property="gagfa">
          <VALUE type="string"></VALUE>
          <VALUE type="None"></VALUE>
     </number>
     <id source="hsfg" class="gfdg" property="fadg">
          <VALUE type="string"></VALUE>
          <VALUE type="None"></VALUE>
     </id>
</process>

任何人都可以提供帮助。真的很感谢:)

试试下面的方法

import xml.etree.ElementTree as ET

xml = '''<process>
     <NAME source="hsfg" class="hshah" property="Name">
          <VALUE type="string"></VALUE>
          <VALUE type="None"></VALUE>
     </NAME>
     <number source="fdsg" class="hgdgf" property="gagfa">
          <VALUE type="string"></VALUE>
          <VALUE type="None"></VALUE>
     </number>
     <id source="ag" class="gfdg" property="fadg">
          <VALUE type="string"></VALUE>
          <VALUE type="None"></VALUE>
     </id>
</process>'''

root = ET.fromstring(xml)
to_change_parent = root.find('.//NAME[@source="hsfg"]')
to_change = to_change_parent.find('VALUE[@type="string"]')
to_change.text = 'new_value'
ET.dump(root)

输出

<process>
     <NAME source="hsfg" class="hshah" property="Name">
          <VALUE type="string">new_value</VALUE>
          <VALUE type="None" />
     </NAME>
     <number source="fdsg" class="hgdgf" property="gagfa">
          <VALUE type="string" />
          <VALUE type="None" />
     </number>
     <id source="ag" class="gfdg" property="fadg">
          <VALUE type="string" />
          <VALUE type="None" />
     </id>
</process>