【问题标题】:Python3 - loop on xml config filePython3 - 在 xml 配置文件上循环
【发布时间】:2019-04-14 17:17:03
【问题描述】:

我想在 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】:
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)

【讨论】:

  • 我尝试在文件&lt;students&gt; &lt;student id="ST1" name="Jhone" /&gt; &lt;student id="ST5" name="Pitter" /&gt; &lt;student id="ST77" name="Arik" /&gt; &lt;/students&gt; 中设置,然后使用您的代码查找root = open ('test.txt').read() # search the document by id student = find_student_by_id(root,'ST1') 之类的学生,但出现错误AttributeError: 'str' object has no attribute 'findall'
  • 查看这里如何将文件加载到 XML doc docs.python.org/3.7/library/xml.etree.elementtree.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-24
相关资源
最近更新 更多