F#Xml类型提供程序测试节点是否存在

前端之家收集整理的这篇文章主要介绍了F#Xml类型提供程序测试节点是否存在前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这似乎应该是微不足道的.我正在解析许多 XML文件,其中一些包含所有预期的节点,其中一些不包含.我需要能够测试节点的存在.我正在使用F#Xml类型提供程序.此代码不起作用,但它说明了我要做的事情.

#r "../../../bin/FSharp.Data.dll"
#r "System.Xml.Linq.dll"
open FSharp.Data

type Author = XmlProvider<"""<author name="Paul Feyerabend" born="1924"><height>10</height></author>""">
let sample = Author.Parse("""<author name="Karl Popper" born="1902" />""")
let containsHeight = sample.Height <> null // I want this to return false

解决方法

XML类型提供程序通过从样本中推断出类型来工作.您可以使用可选的SampleIsList参数提供多个示例:

open FSharp.Data

type Author = XmlProvider<"""
<samples>
    <author name="Paul Feyerabend" born="1924">
        <height>10</height>
    </author>
    <author name="Karl Popper" born="1902" />
</samples>""",SampleIsList = true>

这使您可以加载popper和feyerabend:

let popper = Author.Parse("""<author name="Karl Popper" born="1902" />""")
let feyerabend = Author.Parse("""<author name="Paul Feyerabend" born="1924"><height>10</height></author>""")

您现在可以测试高度是否存在:

> popper.Height.IsSome;;
val it : bool = false
> feyerabend.Height.IsSome;;
val it : bool = true
> feyerabend.Height |> Option.get;;
val it : int = 10

猜你在找的XML相关文章