使用Ansible xml模块从XML文件获取特定属性

时间:2018-06-29 21:09:59

标签: xpath ansible

我有一个如下的XML文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleExecutable</key>
    <string>p4v</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>2018.2</string>
    <key>CFBundleVersion</key>
    <string>2018.2/1666551</string>
    <key>CFBundleGetInfoString</key>
    <string>2018.2, Copyright 2018 Perforce Software, Inc.</string>
    <key>CFBundleIconFile</key>
    <string>application.icns</string>
    <key>P4RevString</key>
    <string>P4V/MACOSX1013X86_64/2018.2/1666551 (2018/05/30)</string>
    <key>NSPrincipalClass</key>
    <string>NSApplication</string>
    <key>NSHighResolutionCapable</key>
    <string>True</string>
    <key>CFBundleName</key>
    <string>P4V</string>
    <key>CFBundleSignature</key>
    <string>P4VC</string>
    <key>CFBundleIdentifier</key>
    <string>com.perforce.p4v</string>
</dict>
</plist>

如何获取密钥2018.2的字符串CFBundleShortVersionString

我尝试了类似下面的方法,但是它列出了所有字符串值,而不是与提供的键匹配的字符串值。

 - xml:
      path: /Applications/p4v.app/Contents/Info.plist
      xpath: /plist/dict[starts-with(key,'CFBundleShortVersionString')]/string
      attribute: CFBundleShortVersionString
      content: 'text'
   register: p4v_version

我认为我在这里提供了错误的xpath,但是找不到正确的xpath。

1 个答案:

答案 0 :(得分:1)

您完全不需要attribute,并且如果没有其他<dict>-s,则可以省略第一个条件。

- xml:
    path: /Applications/p4v.app/Contents/Info.plist
    xpath: /plist/dict/key[.='CFBundleShortVersionString']/following-sibling::*[1]
    content: 'text'
  register: p4v_version