简体   繁体   中英

Need to Replace Element value with Mix Content with lxml etree Python

I have an string containing xml structure. <root><test1>Test 1</test1><test2>Test <dummy>2</dummy> Test</test2><test3>Test 3</test3></root> , now i want to replace values in element <test2> with a mixed content This is a New Input Scenario <AnyElement>Text</AnyElement> Check

Below is my code

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)

Output

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

Expected Output

<root><test1>Test 1</test1><test2>This is a New Input Scenario <AnyElement>Text</AnyElement> Check</test2><test3>Test 3</test3></root>

That's possible using combination of adding new elements and their text / tail properties:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM