简体   繁体   English

从Python中的嵌套编号列表生成XML

[英]Generating XML from nested numbered lists in Python

I have a nested, numbered list structure like this: 我有一个嵌套的编号列表结构,如下所示:

1.1 - "james" 1.1-“詹姆斯”
1.1.1 - "alice" 1.1.1-“驴友”
1.2.1 - "bob" 1.2.1-“鲍勃”

What is the best/fastest way to turn it into an XML structure like this: 将其转换为如下所示的XML结构的最佳/最快方法是什么:

> <1>  
>    <1><james/>
>       <1><alice/></1>
>       <2><bob/></2>
>    </1>  
> </1>  

This is super easy if the depth of the numbered lists is only 3, but in this case it is unknown, maybe up to 6. I'm pretty sure I need to create a recursive self-referential function but need a way of putting each element in its place within the XML structure, which I'm stuck on at the moment. 如果编号列表的深度仅为3,则这非常容易,但是在这种情况下,它是未知的,可能多达6。我很确定我需要创建一个递归自引用函数,但是需要一种将每个元素在XML结构中的位置,此刻我仍然坚持。

Here's a small recursive function that will convert lists to XML strings. 这是一个小的递归函数,它将列表转换为XML字符串。 Adding padding support, or limiting depth is trivial to add, but I'll leave that for you. 添加填充支持或限制深度很简单,但是我会留给您。

def xml(it, depth=1):
 s = ''
 for k, v in enumerate(it):
  s += '<%d>' % (k+1)
  if isinstance(v, list):
   s += xml(v, depth+1)
  else:
    s += str(v)
  s += "</%d>\n" % (k+1)
 return s

Here's an example usage and output. 这是用法和输出示例。

>>> data = ['Names', ['Boy names'], ['Girl Names', ['J-Names', ['Jill', 'Jen']]]]
>>> print xml(data)
'<1>Names</1>
<2><1>Boy names</1>
</2>
<3><1>Girl Names</1>
<2><1>J-Names</1>
<2><1>Jill</1>
<2>Jen</2>
</2>
</2>
</3>'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM