首页 > 解决方案 > 在匹配字典中包含的值的模式后检索整个字典的脚本

问题描述

我在 xml 文件中有这样的字典:

<key>Key1</key>
<dict>
      <key>ChildKey1</key>
      <array>
             <string>String1</string>
             <string>String2</string>
      </array>
      <key>ChildKey2</key>
      <string>String3</string>
      <key>ChildKey3</key>
      <string>ABC</string>
</dict>

<key>Key2</key>
<dict>
      <key>ChildKey1</key>
      <array>
             <string>String1</string>
             <string>String2</string>
      </array>
      <key>ChildKey2</key>
      <string>String3</string>
      <key>ChildKey3</key>
      <string>DEF</string>
</dict>

我需要一个脚本来搜索匹配的模式。找到匹配项后,我需要检索存在匹配值的整个字典。

对于(例如):如果我正在搜索的匹配模式是 ABC,那么我需要检索 Key1 下的整个字典。

我尝试使用 Grep 但无法检索整个字典

标签: bashshell

解决方案


您可以使用 XMLLint 根据 XPath 选择数据:

xmllint --xpath '//dict[.//string/text() = "ABC"]' your_xml_file

这将选择dict包含string文本内容为的节点的每个节点ABC

如果要查找的文本可以在其他节点中找到,string则可以使用通配符:

xmllint --xpath '//dict[.//*/text() = "ABC"]' your_xml_file

为了提高性能,您应该使用比我使用的递归下降更精确的路径,//dict因为我不知道您的整个 XML 结构。


推荐阅读