[英]Python3 - loop on xml config file
I want to build config file in xml that have a key value, and I can loop on keys.我想在具有键值的 xml 中构建配置文件,并且我可以在键上循环。
For example I have 3 student (id and name)例如我有 3 个学生(身份证和姓名)
<students>
<student id="ST1" name="Jhone" />
<student id="ST5" name="Pitter" />
<student id="ST77" name="Arik" />
</students>
How can I put it on xml config file that in python I can check if I have STxx key and get the value?我怎样才能把它放在 xml 配置文件中,在 python 中我可以检查我是否有 STxx 键并获取值?
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.