bash - 在匹配字典中包含的值的模式后检索整个字典的脚本
问题描述
我在 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 但无法检索整个字典
解决方案
您可以使用 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 结构。
推荐阅读
- c# - 从数据表错误中获取值对象与目标类型不匹配
- node.js - CDN文件url需要重定向301还是302?
- sql-server - 将一个数据库表中的行插入另一个数据库的两个不同表中
- php - 我得到空数组,在 Codeigniter 中上传多个图像时需要图像数组
- javascript - 在自定义钩子中测试 fetch.catch
- validation - 在 blazor razor 页面中使用 editform 时如何重置自定义验证错误
- c# - 如何区分来自类内部或外部的依赖属性更改
- java - java ArrayList 和 LinkedList 添加
- javascript - 如何使用 Handlebars 生成网格
- python - 如何找到一堆图像的平均分辨率,以便我可以将尺寸输入 TensorFlow 中的 CNN 层?