Concatenate two XML templates in Python

53 views Asked by At

I have two XML template needed to be added when certain conditions are met. I concatenate doesn't seem to handle them properly.

template1 = \
 '''
    <ParentTag>                                                                      
       <orders orderid="%s">                                                          
         <unitprice>%s</unitprice>                                                  
         <quantity>%s</quantity>                                                                                                               
       </orders>                                     
    </ParentTag>
 '''

template2 = \
 ''' 
   <details>
    <productid>%s</productid>
    <productname>%s</productname>
   </details>

My objective is to get an xml file as below:

  <ParentTag>                                                                      
       <orders orderid="%s">                                                          
         <unitprice>%s</unitprice>                                                  
         <quantity>%s</quantity>                                                                                                               
       </orders>
       <details>
        <productid>%s</productid>
        <productname>%s</productname>
       </details>                                   
    </ParentTag>

Snippet of python code:

  output = ""
  if (condition is met):
     output += output % template1(orderid, unitprice, quantity)
  else:
     output += <template1 + template2>

How do I concatenate both the templates in Python.

1

There are 1 answers

0
Zaxvo On BEST ANSWER

One (unorthodox) way of doing it is like so:

template1 = \
 '''
    <ParentTag>                                                                      
       <orders orderid="%s">                                                          
         <unitprice>%s</unitprice>                                                  
         <quantity>%s</quantity>                                                                                                               
       </orders>%s                                     
    </ParentTag>
 '''

template2 = \
 ''' 
   <details>
    <productid>%s</productid>
    <productname>%s</productname>
   </details>
'''

Code:

output = ""
  if (condition is met):
     output += output % template1(orderid, unitprice, quantity, "")
  else:
     output += template1 % ("%s", "%s, "%s", "\n\t"+template2)

However, I'd argue that there's probably a better way of generating these XML templates than breaking them up into two large ones and concatenating them, but without having more details about your problem this would be my preferred solution.