Home > database >  How loop with Python and increment XML tree
How loop with Python and increment XML tree

Time:01-18

I have this code:

linenum = 1
for g in u.answers:
    attr = ""
    lines.append("\t\t<answer%s>%s</answer>" % (attr, g[0]))
    linenum  = 1

which results in:

<xml>
    <answer>Primary Job Function</answer>
    <answer>Engineering</answer>
    <answer>Size of Company</answer>
    <answer>100</answer>
    <answer>Job Level</answer>
    <answer>Manager</answer>
    <answer>Type of Company</answer>
    <answer>Supplier</answer>
<xml>

Would like to increment and get the following result:

<xml>
    <question1>Primary Job Function</question1>
    <answer1>Engineering</answer1>
    <question2>Size of Company</question2>
    <answer2>100</answer2>
    <question3>Job Level</question3>
    <answer3>Manager</answer3>
    <question4>Type of Company</question4>
    <answer4>Supplier</answer4>
</xml>

CodePudding user response:

attr is assigned to an empty string and never changes. Also the canonical way to count in for loops is to use enumerate and % is a very old method for formatting strings. Try this:

for i, g in enumerate(zip(u.answers[::2], u.answers[1::2])):
    linenum = i   1
    lines.append(f"\t\t<question{linenum}>{g[0]}</question{linenum}>")
    lines.append(f"\t\t<answer{linenum}>{g[1]}</answer{linenum}>")

See this question on how to use zip or pairwise to iterate over pairs in a list.

CodePudding user response:

End up with this approach....

    for i in range (len (u.answers)):
        attr = ""
        if (i%2 == 0):
            lines.append("\t\t<question{0}>{1}</question{0}>".format(i 1, u.answers[i][0]))


    for i in range (len (u.answers)):
        attr = ""
        if (i%2 != 0):
            lines.append("\t\t<answer{0}>{1}</answer{0}>".format(i, u.answers[i][0]))
    
  • Related