Python: How to replace a character in a XML file with a new node?

ぐ巨炮叔叔 提交于 2019-12-25 11:07:02

问题


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 &lt and &gt . 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!