Life is complex
Life is complex

Reputation: 15619

How to add multiple SubElement using lxml.etree? (python)

I would like to use lxml.etree to write out several SubElements under one primary tags with several subtags.

This is the code that I'm using to write out my tags.

def create_SubElement(_parent, _tag, attrib={}, _text=None, nsmap=None, **_extra):
    result = ET.SubElement(_parent, _tag, attrib, nsmap, **_extra)
    result.text = _text
    return result

This is my code that has multiple p_tags.

for key_products in primary_details:
    try:
        if 'Products' in key_products.h3.text:
            for p_tag in key_products.find_all('p'):
                products = create_SubElement(root, 'Products', _text=p_tag.text)

      except:
            continue

print (ET.tostring(root, pretty_print=True))

The code above currently produces this output:

'<root>\n 
    <Products>product name 1 </Products>\n  
    <Products>product name 2 </Products>\n  
    <Products>product name 3 </Products>\n  
    <Products>product name 4 </Products>\n  
    <Products>product name 5 </Products>\n  
</root>\n'

The desired output would be something like this:

'<root>\n 
    <Products>
      <ProductName>product name 1 </ProductName>\n  
      <ProductName>product name 2 </ProductName>\n  
      <ProductName>product name 3 </ProductName>\n  
      <ProductName>product name 4 </ProductName>\n  
      <ProductName>product name 5 </ProductName>\n 
   <Products> 
</root>\n'

Upvotes: 0

Views: 826

Answers (1)

har07
har07

Reputation: 89285

You only need to create Products element once and create multiple ProductName elements using Products as parent, something like this :

....
if 'Products' in key_products.h3.text:
    # create Products element once:
    products = create_SubElement(root, 'Products')
    for p_tag in key_products.find_all('p'):
        # create ProductName element using Products as parent
        productName = create_SubElement(products, 'ProductName', _text=p_tag.text)

Upvotes: 1

Related Questions