【问题标题】:Need to Replace Element value with Mix Content with lxml etree Python需要使用 lxml etree Python 将元素值替换为混合内容
【发布时间】:2020-10-23 11:52:50
【问题描述】:

我有一个包含 xml 结构的字符串。 <root><test1>Test 1</test1><test2>Test <dummy>2</dummy> Test</test2><test3>Test 3</test3></root>,现在我想用混合内容 This is a New Input Scenario <AnyElement>Text</AnyElement> Check 替换元素 <test2> 中的值

下面是我的代码

from lxml import etree as ET

source = "<root><test1>Test 1</test1><test2>Test <dummy>2</dummy> Test</test2><test3>Test 3</test3></root>"
repl = "This is a New Input Scenario <AnyElement>Text</AnyElement> Check"

inp = ET.fromstring(source)

for inputelement in inp.xpath('.//test2'):
    inputelement.text = repl

inp = str(bytearray(ET.tostring(inp)).decode())
print(inp)

输出

&lt;root&gt;&lt;test1&gt;Test 1&lt;/test1&gt;&lt;test2&gt;This is a New Input Scenario &amp;lt;AnyElement&amp;gt;Text&amp;lt;/AnyElement&amp;gt; Check&lt;dummy&gt;2&lt;/dummy&gt; Test&lt;/test2&gt;&lt;test3&gt;Test 3&lt;/test3&gt;&lt;/root&gt;

预期输出

&lt;root&gt;&lt;test1&gt;Test 1&lt;/test1&gt;&lt;test2&gt;This is a New Input Scenario &lt;AnyElement&gt;Text&lt;/AnyElement&gt; Check&lt;/test2&gt;&lt;test3&gt;Test 3&lt;/test3&gt;&lt;/root&gt;

【问题讨论】:

    标签: python xml lxml


    【解决方案1】:

    这可以通过添加新元素及其text / tail 属性的组合来实现:

    from lxml import etree as ET
    
    source = "<root><test1>Test 1</test1><test2>Test <dummy>2</dummy> Test</test2><test3>Test 3</test3></root>"
    
    # split mixed content into parts: text / element / text
    repl1 = "This is a New Input Scenario "
    repl2 = '<AnyElement>Text</AnyElement>'
    repl3 = ' Check'
    
    inp = ET.fromstring(source)
    
    for inputelement in inp.xpath('.//test2'):
        # first attach text
        inputelement.text = repl1
        # create new element and attach final part to its tail
        anyelement = ET.XML(repl2)
        anyelement.tail = repl3
        # replace original dummy element with new one
        inputelement.replace(inputelement.find('dummy'), anyelement)
        
    
    inp = str(bytearray(ET.tostring(inp)).decode())
    print(inp)
    

    【讨论】:

    • 这对于当前场景是正确的,但是如果 Mix 内容本身有多个嵌套怎么办。实际上我正在研究段落,其中将包含多个列表和表格,需要一次插入。
    猜你喜欢
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多