Python3 - 在xml配置文件上循环

问题描述 投票:-1回答:1

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

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

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

如何将它放在xml配置文件中,在python中我可以检查我是否有STxx密钥并获取值?

python xml python-3.x configuration
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.