简体   繁体   中英

Any other possible way for XML text insertion in python?

My problem is not finding the word "my" in the ex

Here's my snippet:

from xml.dom import minidom
import re

def prettify(elem):
  rs = et.tostring(elem,encoding='utf-8')
  rp = minidom.parseString(rs)
  return rp.toprettyxml(indent="  ")

root=et.Element('my_root')

et.SubElement(root, 'my_element')
root[0].text = 'hello my world'
print(prettify(root))

a,b = re.search("my", root[0].text).span()
print(f'position of \'my\': [{a}:{b}]')

t = root[0].text
l = [t[:a], '<red>', t[a:b], '</red>', t[b:]]
print(l)

root[0].text = ''.join(l)
print(prettify(root))

My problem is how to insert the XML correctly.

The last output of print(prettify(root)) shows now

<my_element>hello &lt;red&gt;my&lt;/red&gt; world</my_element>

in the relevant line.That's not what I want.

I want

<my_element>hello <red>my</red> world</my_element>

instead. Is that possible at all?

If yes, then tell me how?

The code below should do that

from xml.etree.ElementTree import Element, SubElement
import xml.etree.ElementTree as ET

root = Element('my_element')
root.text = 'hello'
child = SubElement(root, 'red')
child.text = 'my'
child.tail = 'world'
ET.dump(root)

output

<my_element>hello<red>my</red>world</my_element>

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