gpt4 book ai didi

c# - C# 的 F# Xml TypeProvider

转载 作者:太空狗 更新时间:2023-10-30 00:10:53 25 4
gpt4 key购买 nike

有没有等价于F# TypeProvider的在 C# 中?我正在寻找使用 C# 读取 Xml 文件的最简单方法。在这一点上,我打算使用 XDocument,但我想知道是否有更好的东西。

F# 使读取 Xml 文件变得如此容易,以至于我想知道我是否应该为 Xml 处理切换语言!

最佳答案

如前所述,C# 不支持类型提供程序并且没有简单的方法来模拟它们(正如 Gustavo 提到的,您可以通过一个小型 F# 库使用生成的类型提供程序,但是 XML、JSON , CSV 等不是这种。)

我认为使用 F# 库进行处理是最好的方法。

更复杂的替代方法是编写代码,让您定义类型以在 C# 中为 XML 文件建模,然后自动将文件读入这些类。我认为这样的东西不存在,但我在 F# 中写了一个类似的东西(在类型提供程序之前),所以你可以看到 the snippet for inspiration .用法如下所示:

// Modelling RSS feeds - the following types define the structure of the
// expected XML file. The StructuralXml parser can automatically read
// XML file into a structure formed by these types.
type Title = Title of string
type Link = Link of string
type Description = Description of string

type Item = Item of Title * Link * Description
type Channel = Channel of Title * Link * Description * list<Item>
type Rss = Rss of Channel

// Load data and specify that names in XML are all lowercase
let url = "http://feeds.guardian.co.uk/theguardian/world/rss"
let doc : StructuralXml<Rss> =
StructuralXml.Load(url, LowerCase = true)

// Match the data against a type modeling the RSS feed structure
let (Rss(channel)) = doc.Root
let (Channel(_, _, _, items)) = channel
for (Item(Title t, _, _)) in items do
printfn "%s" t

关于c# - C# 的 F# Xml TypeProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com