使用Python插入XML元素

问题描述 投票:0回答:1

我有一个快速而脏的构建脚本,需要在一个小的xml配置文件中更新几行。由于文件太小,我使用一个公认的低效过程来更新文件,只是为了简单起见:

def hide_osx_dock_icon(app):
    for line in fileinput.input(os.path.join(app, 'Contents', 'Info.plist'), inplace=True):
        line = re.sub(r'(<key>CFBundleDevelopmentRegion</key>)', '<key>LSUIElement</key><string>1</string>\g<1>', line.strip(), flags=re.IGNORECASE)

    print line.strip()

我们的想法是找到<key>CFBundleDevelopmentRegion</key>文本并在其前面插入LSUIElement内容。我在另一个区域做了这样的事情并且工作正常,所以我想我只是错过了一些东西,但是我没有看到它。

我究竟做错了什么?

python regex xml python-2.7
1个回答
0
投票

您只打印最后一行,因为您的print语句不在for循环中:

for line in fileinput.input(os.path.join(app, 'Contents', 'Info.plist'), inplace=True):
    line = re.sub(r'(<key>CFBundleDevelopmentRegion</key>)', '<key>LSUIElement</key><string>1</string>\g<1>', line.strip(), flags=re.IGNORECASE)

print line.strip()

缩进该行以匹配前一行:

for line in fileinput.input(os.path.join(app, 'Contents', 'Info.plist'), inplace=True):
    line = re.sub(r'(<key>CFBundleDevelopmentRegion</key>)', '<key>LSUIElement</key><string>1</string>\g<1>', line.strip(), flags=re.IGNORECASE)

    print line.strip()
© www.soinside.com 2019 - 2024. All rights reserved.