使用elementtree获取和更新xml中的值

时间:2018-01-24 12:22:17

标签: python xml elementtree

我是一个xml文件,我想在Python 3.4中使用ElementTree来更新其中的值。我坚持使用ElementTree与其他代码保持一致。

该文件如下:

<Details>
    <Attrib name="Name">bill</Attrib>
    <Attrib name="Email">bill.jones@mail.com</Attrib>
    <Attrib name="Phone">555-000-555</Attrib>
</Details>

 import xml.etree.ElementTree as ET
 tree = ET.parse('file.xml')
 root = tree.getroot()
      for child in root:
          print("Tag: {0} Attrib: {1}".format(child.tag, child.attrib))

输出结果为:

Tag: Attrib Attrib: {'name': 'Name'}
Tag: Attrib Attrib: {'name': 'Email'}
Tag: Attrib Attrib: {'name': 'Phone'}

如何获得“电话”的价值?所以我想得到&#39; 555-000-555并将其更新为另一个值?

3 个答案:

答案 0 :(得分:2)

使用text属性:

xmlstr = '''<Details>
    <Attrib name="Name">bill</Attrib>
    <Attrib name="Email">bill.jones@mail.com</Attrib>
    <Attrib name="Phone">555-000-555</Attrib>
</Details>'''

import xml.etree.ElementTree as ET
root = ET.fromstring(xmlstr)
for child in root:
    child.text += ' (changed)'
    print("Tag: {0} text: {1}".format(child.tag, child.text))

这将输出:

Tag: Attrib text: bill (changed)
Tag: Attrib text: bill.jones@mail.com (changed)
Tag: Attrib text: 555-000-555 (changed)

答案 1 :(得分:0)

使用&#34; child.text&#34;,例如:

print(child.attrib +&#34;:&#34; + child.text)

答案 2 :(得分:0)

要更新具有属性Attrib的特定节点[@name="Phone"]的值,请使用简短解决方案:

import xml.etree.ElementTree as ET

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

phone = root.find('Attrib[@name="Phone"]')
phone.text = '777-000-777'

print(ET.dump(root))    # ET.dump() - This function should be used for debugging only.

输出:

<Details>
    <Attrib name="Name">bill</Attrib>
    <Attrib name="Email">bill.jones@mail.com</Attrib>
    <Attrib name="Phone">777-000-777</Attrib>
</Details>