tags:

views:

56

answers:

1

I needed some really simple XML output so I decided to write my own functions. This was just the first step, but something has gone terribly wrong. While I would expect the output to look like this:

<A>
    <D>
        <I></I>
        <J></J>
        <K></K>
    </D>
    <E>
        <I></I>
        <J></J>
        <K></K>
    </E>

...and so on.

Instead the output looks like this:

  <I></I>
  <J></J>
  <K></K>
 <D>
 </D>
 <E>
 </E>
 <F>
 </F>
 <G>
 </G>
 <H>
 </H>
<A>
</A>
<B>
</B>
<C>
</C>

I'm sure my mistake is something very simple, but I just can't see it. This is the entire file that I'm using:

def XMLChild(list, depth):
    for arg in list:
        print '\t' * depth + '<' + arg + '></' + arg + '>'

def XMLParent(list, depth, child):
    for arg in list:
        print '\t' * depth + '<' + arg + '>'
        child
        print '\t' * depth + '</' + arg + '>'

list1 = ['A', 'B', 'C']
list2 = ['D', 'E', 'F', 'G', 'H']
list3 = ['I', 'J', 'K', ]

XMLParent(list1, 0, XMLParent(list2, 1, XMLChild(list3, 2)))

As you can see, both functions are supposed to print tags. XMLParent should allow the passing of a child function, either another parent or a child. No matter how much I look at it I can't figure out why it's printing the way it is.

+2  A: 

You're not returning the result, but rather printing it directly. Therefore it will be outputted in the order that the functions execute. Your code is equivalent to the following, which clarifies the order in which the functions are called:

a = XMLChild(list3, 2)
b = XMLParent(list2, 1, a)
XMLParent(list1, 0, b)

Try building a string in each of the functions, returning it to the caller. The caller can then append it to it's own string buffer and in turn return it. Then you can output the combined string like such, and do all the printing in a single place:

a = XMLChild(list3, 2)
b = XMLParent(list2, 1, a)
print XMLParent(list1, 0, b)
Emil H
Ah, I get it. I think that will also make my next step, to modify it to print to a file, easier. Thank you so much.
xnine