lxml.etree insert elements into element.text

后端 未结 1 1073
面向向阳花
面向向阳花 2021-01-23 03:50

I have strings that have empty xml elements in them, like this:

>>> s = \"\"\"fizz buzz  bananas\"\"\"

These strin

相关标签:
1条回答
  • 2021-01-23 04:27

    You could make your input string a well-formed XML document (with text as the root element) and parse that into an Element object using fromstring(). Then append it to the parent.

    from lxml import etree as et
    
    s1 = """foo bar <pb n="42"/> parrots like <pb n="43"/> eggs and spam"""
    s2 = "<text>{0}</text>".format(s1)
    
    text = et.fromstring(s2)
    root = et.Element('root')
    root.append(text)
    
    et.dump(root)
    

    Output:

    <root>
     <text>foo bar <pb n="42"/> parrots like <pb n="43"/> eggs and spam</text>
    </root>
    
    0 讨论(0)
提交回复
热议问题