使用Python插入XML元素

时间:2013-06-20 11:58:04

标签: python regex xml python-2.7

我有一个快速而脏的构建脚本,需要在一个小的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内容。我在另一个区域正在做这样的事情并且工作正常所以我想我只是错过了一些东西,但我没有看到它。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您只打印 last 行,因为您的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()