ruby yaml ypath 和 xpath 一样吗?
您好,我有一个像这样的 yaml 文件,
---
data:
- date: "2004-06-11"
description: First description
- date: "2008-01-12"
description: Another descripion
我如何执行类似于 xml 的 xpath 的“ypath”查询?类似“获取日期为 2004-06-11 的描述”之类的内容,
YAML.parse_file('myfile.yml').select('/data/*/date == 2004-06-11')
你是如何做到的,如果可能的话,我如何通过 'ypath' 类似地编辑描述?
谢谢
Hi i have a yaml file like so
---
data:
- date: "2004-06-11"
description: First description
- date: "2008-01-12"
description: Another descripion
How can i do a "ypath" query similar to xpath for xml ? Something like "get the description where the date is 2004-06-11"
YAML.parse_file('myfile.yml').select('/data/*/date == 2004-06-11')
How do you do it, and if that's possible how can i similarly edit the description by 'ypath' ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确实有像YPath这样的东西:github.com/peterkmurphy/YPath-Specification< /a>
它是在 Ruby 的 YAML 库中实现的;请参阅 BaseNode#search 的文档。
There is indeed such thing as YPath: github.com/peterkmurphy/YPath-Specification
And it's implemented in Ruby's YAML lib; see the doc for BaseNode#search.
如果 Ruby 不是硬性约束,您可以查看 dpath 工具。
它为 YAML(和其他)文件提供类似 xpath 的查询语言。也许打电话
它在外部过滤您的数据。
If Ruby is not a hard constraint you might take a look at the dpath tool.
It provides an xpath-like query language to YAML (and other) files. Maybe call
it externally to filter your data.
yaml 文件描述了从字符串到哈希数组(从字符串映射到字符串)的哈希映射。没有用于嵌套哈希的 xpath 之类的东西(至少在标准库中没有),但是使用标准 Hash 和 Enumerable 方法就足够简单了:
要更改描述,您可以简单地执行
item["description"] =“新描述”
,然后使用hash.to_yaml
将哈希序列化回 YAML。The yaml file describes a hash mapping from strings to arrays of hashes that map from strings to strings. There is no such thing as xpath for nested hashes (at least not in the standard library), but it's simple enough with standard Hash and Enumerable methods:
To change the description, you can then simply do
item["description"] = "new description"
and then serialize the hash back to YAML usinghash.to_yaml
.