简体   繁体   中英

Generating XML from nested numbered lists in Python

I have a nested, numbered list structure like this:

1.1 - "james"
1.1.1 - "alice"
1.2.1 - "bob"

What is the best/fastest way to turn it into an XML structure like this:

> <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.

Here's a small recursive function that will convert lists to XML strings. 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>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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