0

我正在尝试在 python 中创建一个函数,该函数将接受任何排序(字典/参数)和参数数量以递归地构建 xml 树。但是我似乎无法弄清楚逻辑。这是我到目前为止所拥有的:

from lxml import etree as e

def CreateSubNode(top, *args, **kwargs): 
    root = e.Element(top)
    for key, val in kwargs.items():
        if type(val) == dict:
            return CreateSubNode(key, **val)
        c = e.Element(key)
        c.text = str(val)
        root.append(c)
    return root

details = {'name':'someguy', 'age':'23'}
address = {'city':'sometown', 'state':'somestate'}

final = CreateSubNode(top = 'information', details=details, address=address)
text_buf = e.tostring(final, pretty_print=True)
print text_buf

我的输出是:

<details>
  <age>23</age>
  <name>someguy</name>
</details>

它在第一个参数之后没有打印任何内容,也没有创建父节点(在本例中为信息)。对我做错了什么有帮助吗?我不太擅长递归...

4

2 回答 2

0

所以我在发布问题后立即想通了:

def CreateSubNode(top, *args, **kwargs): 
    root = e.Element(top)
    for key, val in kwargs.items():
        if type(val) == dict:
            c = CreateSubNode(key, **val)
        else:
            c = e.Element(key)
            c.text = str(val)
        root.append(c)
    return root
于 2013-06-06T23:08:59.063 回答
0

您必须保存递归结果:

def CreateSubNode(top, *args, **kwargs):
    root = e.Element(top)
    for key, val in kwargs.items():
        if type(val) == dict:
            c = CreateSubNode(key, **val)
        else:
            c = e.Element(key)
            c.text = str(val)
        root.append(c)
    return root
于 2013-06-06T23:09:07.410 回答