问题描述
是否可以使用 Yaml.DotNet 或其他库从 c# 动态构建 Yaml 文档?
Is it possible to build a Yaml document dynamically from c# with Yaml.DotNet or another library?
我了解如何使用序列化来完成此操作,但这需要从对象结构开始.
I understand how this can be done using serialisation, however that requires starting with an object structure.
我正在寻找一种方法来动态创建 Yaml 文档节点,就像使用 Xml 使用 XElement.Add(object) 方法一样.
I'm looking to find a way to create the Yaml document nodes on the fly as you would with Xml using the XElement.Add(object) method for example.
推荐答案
你可以使用 YamlDotNet.您首先创建一个 YamlStream,添加一个或更多 document 到它,然后你可以添加 序列, 映射 和 标量.
You can do that using YamlDotNet. You start by creating a YamlStream, add one or more document to it, then you can add sequences, mappings and scalars to it.
这里是一个例子:
var address = new YamlMappingNode(
new YamlScalarNode("street"),
new YamlScalarNode("123 Tornado Alley
Suite 16") { Style = YamlDotNet.Core.ScalarStyle.Literal },
new YamlScalarNode("city"),
new YamlScalarNode("East Westville"),
new YamlScalarNode("state"),
new YamlScalarNode("KS")
) { Anchor = "main-address" };
var stream = new YamlStream(
new YamlDocument(
new YamlMappingNode(
new YamlScalarNode("repeipt"),
new YamlScalarNode("Oz-Ware Purchase Invoice"),
new YamlScalarNode("date"),
new YamlScalarNode("2007-08-06"),
new YamlScalarNode("customer"),
new YamlMappingNode(
new YamlScalarNode("given"),
new YamlScalarNode("Dorothy"),
new YamlScalarNode("family"),
new YamlScalarNode("Gale")
),
new YamlScalarNode("items"),
new YamlSequenceNode(
new YamlMappingNode(
new YamlScalarNode("part_no"),
new YamlScalarNode("A4786"),
new YamlScalarNode("descrip"),
new YamlScalarNode("Water Bucket (Filled)"),
new YamlScalarNode("price"),
new YamlScalarNode("1.47"),
new YamlScalarNode("quantity"),
new YamlScalarNode("4")
),
new YamlMappingNode(
new YamlScalarNode("part_no"),
new YamlScalarNode("E1628"),
new YamlScalarNode("descrip"),
new YamlScalarNode("High Heeled "Ruby" Slippers"),
new YamlScalarNode("price"),
new YamlScalarNode("100.27"),
new YamlScalarNode("quantity"),
new YamlScalarNode("1")
)
),
new YamlScalarNode("bill-to"), address,
new YamlScalarNode("ship-to"), address,
new YamlScalarNode("specialDelivery"),
new YamlScalarNode("Follow the Yellow Brick
" +
"Road to the Emerald City.
" +
"Pay no attention to the
" +
"man behind the curtain.")
{
Style = YamlDotNet.Core.ScalarStyle.Literal
}
)
)
);
这篇关于从 c# 动态构建 Yaml 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!