3

I have an lxml element with children built like this:

xml = etree.Element('presentation')
format_xml = etree.SubElement(xml, 'format')
content_xml = etree.SubElement(xml, 'slides')

I then have several strings that I would like it iterate over and add each as child element to slides. Each string will be something like this:

<slide1>
    <title>My Presentation</title>
    <subtitle>A sample presentation</subtitle>
    <phrase>Some sample text
        <subphrase>Some more text</subphrase>
    </phrase>
</slide1>

How can I append these strings as children to the slides element?

0

2 Answers 2

4

Just append:

import lxml.etree as etree

xml = etree.Element('presentation')
format_xml = etree.SubElement(xml, 'format')
content_xml = etree.SubElement(xml, 'slides')
new = """<slide1>
    <title>My Presentation</title>
    <subtitle>A sample presentation</subtitle>
    <phrase>Some sample text
        <subphrase>Some more text</subphrase>
    </phrase>
</slide1>"""


content_xml.append(etree.fromstring(new))


print(etree.tostring(xml,pretty_print=1))

Which will give you:

<presentation>
  <format/>
  <slides>
    <slide1>
    <title>My Presentation</title>
    <subtitle>A sample presentation</subtitle>
    <phrase>Some sample text
        <subphrase>Some more text</subphrase>
    </phrase>
</slide1>
  </slides>
</presentation>
Sign up to request clarification or add additional context in comments.

Comments

1

fromstring() function would load an XML string directly into an Element instance which you can append:

from lxml import etree as ET

slide = ET.fromstring(xml_string)
content_xml.append(slide)

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.