从xml树迭代器返回结果

时间:2019-06-03 15:11:07

标签: xml python-3.x recursion lxml

我有一个xml树:

<root>
    <expression>
        <add>
            <number>1</number>
            <number>2</number>
            <number>3</number>
        </add>
    </expression>
</root>

我的函数遍历树,添加子文本的int。 print语句的最终结果是我需要的结果,但是如何从addleafnodes函数返回它呢?

root = etree.XML(request.data['expression'])
results = 0

def addleafnodes(root, results):
    for child in root:
        if root.tag != "root" and root.tag != "expression":
            results += int(child.text)
        print(results)
        addleafnodes(child, results)

newresults = addleafnodes(root, results)

2 个答案:

答案 0 :(得分:1)

您将results递归递归,然后递增,但不要将其返回“上”。如果results是一个对象,而您只是传递了一个引用,则可以在对addleafnodes进行根调用之后查看它。

以下内容将总和返回到递归:

from xml.etree.ElementTree import XML

expr = """<root>
    <expression>
        <add>
            <number>1</number>
            <number>2</number>
            <number>3</number>
        </add>
    </expression>
</root>
"""
root = XML(expr)

def addleafnodes(root, results):
    for child in root:
        if root.tag != "root" and root.tag != "expression":
            results += int(child.text)
        results = addleafnodes(child, results)
    return results

newresults = addleafnodes(root, 0)
print(newresults)

我认为这种功能性方法不错,但是您也可以从递归内部简单地更新全局变量(我已从此代码段中删除了results = 0)。

请注意,我不确定代码是否会因较深的表达式结构(例如嵌套的添加等)而中断。

答案 1 :(得分:0)

您的问题被标记为lxml。如果您确实在使用lxml,则可以使用sum() xpath函数来简化...

from lxml import etree

expr = """<root>
    <expression>
        <add>
            <number>1</number>
            <number>2</number>
            <number>3</number>
        </add>
    </expression>
</root>
"""

root = etree.fromstring(expr)


def addleafnodes(elem):
    return int(elem.xpath("sum(.//add/number)"))


newresults = addleafnodes(root)
print(newresults)

打印输出...

6

see here for more info on xpath in lxml