问题
I want to replace all instances of semicolon ":" in my node below with a new node "<colon/>" as shown below.
I want this:
<shortName>Trigger:Digital Edge:Source</shortName>
to become like this:
<shortName>Trigger<colon/>Digital Edge<colon/>Source</shortName>
I have already tried using search and replace string, but when I get the output all the "< >" change to < and > . Can anyone please suggest any techniques to do this. Thank You
回答1:
The idea is to get the node text, split it by colon and add one by one while setting .tail for every colon:
import xml.etree.ElementTree as ET
data = """<?xml version="1.0" encoding="UTF-8" ?>
<body>
<shortName>Trigger:Digital Edge:Source</shortName>
</body>"""
tree = ET.fromstring(data)
for element in tree.findall('shortName'):
items = element.text.split(':')
if not items:
continue
element.text = items[0]
for item in items[1:]:
colon = ET.Element('colon')
colon.tail = item
element.append(colon)
print ET.tostring(tree)
Prints:
<body>
<shortName>Trigger<colon />Digital Edge<colon />Source</shortName>
</body>
来源:https://stackoverflow.com/questions/25598956/python-how-to-replace-a-character-in-a-xml-file-with-a-new-node