Python3-在xml配置文件上循环

时间:2019-04-14 17:17:04

标签: python xml python-3.x configuration

我想在具有键值的xml中构建配置文件,并且可以循环使用键。

例如,我有3个学生(身份证和姓名)

<students>
<student id="ST1" name="Jhone" />
<student id="ST5" name="Pitter" />
<student id="ST77" name="Arik" />
</students> 

如何将其放在xml配置文件中,以便在python中检查是否具有STxx键并获取值?

1 个答案:

答案 0 :(得分:0)

import xml.etree.ElementTree as ET

STUDENTS = [('ST1','Jhone'),('ST5','Pitter'),('ST77','Arik')]

def indent(elem, level=0):
    i = "\n" + level*"  "
    j = "\n" + (level-1)*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for subelem in elem:
            indent(subelem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = j
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = j
    return elem 

def find_student_by_id(doc,_id):
  arg = ".//student[@id='{}']".format(_id)
  return doc.findall(arg)

# build the XML document
root = ET.Element('students')
for student in STUDENTS:
    student_element = ET.SubElement(root, 'student')
    student_element.set('name',student[1])
    student_element.set('id',student[0])

# print the xml document
indent(root)
ET.dump(root)

# search the document by id
student = find_student_by_id(root,'ST1')
# found
print(student)
student = find_student_by_id(root,'ST111')
# not found
print(student)