【问题标题】:Inserting an XML Element w/ Python使用 Python 插入 XML 元素
【发布时间】:2013-06-20 11:58:03
【问题描述】:

我有一个快速而肮脏的构建脚本,需要更新一个小的 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()

这个想法是找到&lt;key&gt;CFBundleDevelopmentRegion&lt;/key&gt; 文本并在它前面插入LSUIElement 内容。我正在另一个领域做类似的事情,它工作正常,所以我想我只是错过了一些东西,但我没有看到它。

我做错了什么?

【问题讨论】:

  • 您只打印最后一行,因为print 行缩进不够远。这是发帖错误吗?
  • 啊,不。不,这不是一个错误。好吧,反正不在帖子里。那是我看不到的部分。如果您将此作为答案,我会将其标记为 the 答案。感谢您提供额外的眼球。
  • 完成;到过那里,做到了,橡皮鸭知道所有的秘密并且不告诉任何人。

标签: python regex xml python-2.7


【解决方案1】:

您只打印 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-03
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多