Python etree在删除后附加元素

时间:2017-07-26 11:19:30

标签: python python-3.x elementtree

我希望能够删除并附加问题。这在大多数情况下都有效,但是当新问题与先前删除的问题具有相同的q_nr时,附加功能不起作用。

我有一个看起来像这样的xml文件。

<question>
    <q_nr>Q1</q_nr>
    <other />
</question
<question>
    <q_nr>Q2</q_nr>
    <other />
</question

删除功能:

def quest_del(request):
    q_nr = request.POST['deleteQnr']
    tree = ET.parse(filename)
    root = tree.getroot()
    for quest in root.findall('project/question'):
        qt_nr = quest.find('q_nr').text
        if qt_nr == q_nr:
            for child in list(quest):
                quest.remove(child)
    for proj in root.findall('project'):
        for quest in proj.findall('question'):
            result = len(quest.getchildren())
            if result == 0:
                proj.remove(quest)
    tree.write(file_name)

附加功能:

def quest_adder(request):
    tree = ET.parse(source)
    proj = tree.getroot().find("project")
    q_text = ET.SubElement(proj, "question")
    q_text.text = "\n\t\t"
    q_text.tail = "\n\t"
    q_nr = ET.SubElement(q_text, q_nr)
    q_nr.text = request.POST['quest_nr']
    q_nr.tail = "\n\t\t"
    tree.write(filename)

0 个答案:

没有答案