0

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.

2

1 Answer 1

1

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>'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.