【问题标题】:Insert element with LXML and set attribute and text使用 LXML 插入元素并设置属性和文本
【发布时间】:2021-09-28 07:59:09
【问题描述】:

我想多次插入具有相同标签的元素,每次使用 LXML 具有不同的内容和属性。虽然插入元素很容易,但如何获取新创建的元素来设置其文本和属性?

text = ['First', 'Second', 'Third']

for i, t in enumerate(text):
    parent.insert(i, etree.Element('tspan')
    # Now, what object should I use to set text and attrib?

【问题讨论】:

    标签: python xml lxml


    【解决方案1】:

    使用 ElementTree(不需要外部库)

    import xml.etree.ElementTree as ET
    
    xml = '''<root></root>'''
    text = ['First', 'Second', 'Third']
    
    root = ET.fromstring(xml)
    for txt in text:
        sub = ET.SubElement(root,'tspan')
        sub.text = txt
    ET.dump(root)
    

    输出

    <?xml version="1.0" encoding="UTF-8"?>
    <root>
       <tspan>First</tspan>
       <tspan>Second</tspan>
       <tspan>Third</tspan>
    </root>
    

    【讨论】:

    • 谢谢,这似乎也适用于 LXML。我不知道 SubElement 方法返回新创建的元素,与 insert 相反。
    猜你喜欢
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多