【问题标题】:Python: How to replace a character in a XML file with a new node?Python:如何用新节点替换 XML 文件中的字符?
【发布时间】:2014-09-01 04:44:09
【问题描述】:

我想将下面节点中的所有分号“:”实例替换为新节点“”,如下所示。

我想要这个:

触发器:数字边缘:源

变成这样:

触发器数字边缘来源

我已经尝试过使用搜索和替换字符串,但是当我得到输出时,所有的“”都变成了 &lt 和 &gt 。 谁能建议任何技术来做到这一点。 谢谢你

【问题讨论】:

    标签: python xml elementtree xml.etree


    【解决方案1】:

    想法是获取节点文本,用冒号分割并一个一个添加,同时为每个冒号设置.tail

    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)
    

    打印:

    <body>
        <shortName>Trigger<colon />Digital Edge<colon />Source</shortName>
    </body>
    

    【讨论】:

    • 这对我来说非常有效。谢谢你的快速反应。不过还有一件事。当我漂亮地打印 XML 时, 进入一个新行。我希望整个 shortName 为一行,如上所示。有没有办法做到这一点?
    猜你喜欢
    • 2012-01-04
    • 2019-08-17
    • 1970-01-01
    • 2017-10-19
    • 2011-04-12
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多