使用lxml将字符串添加为子元素

时间:2016-04-18 14:36:10

标签: python xml lxml

我有一个lxml元素,其子代构建如下:

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

然后我有几个字符串,我希望它迭代并将每个字符串添加为幻灯片的子元素。每个字符串都是这样的:

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

如何将这些字符串作为子元素附加到slide元素?

2 个答案:

答案 0 :(得分:2)

只需追加:

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))

哪个会给你:

<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>

答案 1 :(得分:1)

fromstring()函数会将XML字符串直接加载到您可以附加的Element实例中:

from lxml import etree as ET

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