xmllint - 无法读取特殊字符

标签 xml linux bash xpath xmllint

<分区>

在 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

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

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

<?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

以上命令不返回任何内容。我所做的只是更改 key 名称,现在它不起作用。有人可以帮忙吗?

最佳答案

(您显示的 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)。

关于xmllint - 无法读取特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34620075/

相关文章:

xml - Google 地球 KML 解析错误

C# : the close method of Xml. 加载(文件)

c# - 在内存中打开 XML 字符串作为 Excel 工作簿而不使用 Windows 窗体 C# 保存

xml - 使用 Wix 从控制面板使用快捷方式卸载 exe

git - 为什么这是我的 .gitconfig 的错误配置行?

linux - 如何永久设置GOPATH环境变量

linux - 测试 SSL 性能的工具

linux - cat file1 file2 2> err命令的输出是什么?

linux - 如何使脚本文件在 ubuntu 的多个终端上运行多个命令?

linux - 如何使用 <ctrl>c 从 script-1.sh 杀死 script-0.sh?