xmllint - 无法读取特殊字符

xmllint - unable to read special characters

在 bash shell 提示符下,我想 运行 xmllint 从 xml 文件中获取数据。让我们看看我没有问题的文件:

查看 fruits.xml 文件:

      <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
  <string name="mykey">grapes</string>
</map>

这是我使用 xmllint 从 fruits.xml

获取值 "grapes"
xmllint --xpath "string(/map/string[@name = 'mykey'])" fruits.xml

我得到以下输出:

$ grapes

很好,我得到了值,但这不是我需要使用的实际密钥。 "mykey" 应该是 "c1:fruits_id-%1$s"

现在,当我将 fruits.xml 文件中的 "mykey" 值更改为另一个值时,我无法从 xmllint 获得任何 return 值:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
  <string name="c1:fruits_id-%1$s">grapes</string>
</map>


xmllint --xpath "string(/map/string[@name = 'c1:fruits_id-%1$s'])" fruits.xml

上面的命令return没什么。我所做的只是更改密钥名称,现在它不起作用。有人可以帮忙吗?

(您显示的 XML 文档在属性值前面没有 c1: - 我猜是打字错误?)

如果您在 shell 命令中使用 $,它会被解释为一个变量并且变量插值开始。因为变量不存在,所以它被替换为空。您可以通过将 XML 文档更改为

来对此进行测试
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
  <string name="c1:fruits_id-%1">grapes</string>
</map>

唯一的变化是删除了$s两个字符。现在路径表达式找到字符串:

$ xmllint --xpath "string(/map/string[@name = 'c1:fruits_id-%1$s'])" fruit.xml
grapes

或者像 Biffen 已经建议的那样将字符转义为 $

$ xmllint --xpath "string(/map/string[@name = 'c1:fruits_id-%1$s'])" fruit.xml
grapes

或者,同样简单,交换引号:

$ xmllint --xpath 'string(/map/string[@name = "c1:fruits_id-%1$s"])' fruit.xml
grapes

由单引号分隔的字符串没有变量插值,即使其中有双引号(参见 this question)。