2

如何使用F# Data 的 XML Type Provider访问父节点的属性?假设我有以下 XML:

<?xml version="1.0" encoding="UTF-16"?>
<ROOT>
    <level1 name="level1Name1" x="8">
        <level2 name="level2Name1" a="8" b="104" />
        <level2 name="level2Name2" a="85" b="140" />
    </level1>
    <level1 name="level1Name2" x="10">
        <level2 name="level2Name3" a="50" b="500" />
        <level2 name="level2Name4" a="376" b="1065" />
        <level2 name="level2Name5" a="10" b="100" />
        <level2 name="level2Name6" a="700" b="700" />
    </level1>
    <level1 name="level1Name3" x="7">
        <level2 name="level2Name7" a="502" b="66" />
    </level1>
</ROOT>

我想在下面的代码中使用它:

open System
open System.Xml.Linq
open FSharp.Data

type myXmlType = XmlProvider<"""<?xml version="1.0" encoding="UTF-16"?><ROOT><level1 name="level1Name1" x="8"><level2 name="level2Name1" a="8" b="104" /><level2 name="level2Name2" a="85" b="140" /></level1><level1 name="level1Name2" x="10"><level2 name="level2Name3" a="50" b="500" /><level2 name="level2Name4" a="376" b="1065" /><level2 name="level2Name5" a="10" b="100" /><level2 name="level2Name6" a="700" b="700" /></level1><level1 name="level1Name3" x="7"><level2 name="level2Name7" a="502" b="66" /></level1></ROOT>""">

let myXml = myXmlType.Parse("""<?xml version="1.0" encoding="UTF-16"?><ROOT><level1 name="level1Name1" x="8"><level2 name="level2Name1" a="8" b="104" /><level2 name="level2Name2" a="85" b="140" /></level1><level1 name="level1Name2" x="10"><level2 name="level2Name3" a="50" b="500" /><level2 name="level2Name4" a="376" b="1065" /><level2 name="level2Name5" a="10" b="100" /><level2 name="level2Name6" a="700" b="700" /></level1><level1 name="level1Name3" x="7"><level2 name="level2Name7" a="502" b="66" /></level1></ROOT>""")

let howToDoIt =
    myXml.GetLevel1s()
    |> Seq.collect (fun L1 -> L1.GetLevel2s())
    |> Seq.tryFind (fun L2 -> L2.b = L1.x * L2.a) // *REMARK
    |> function
    | None -> ""
    | Some L2 -> L2.Name

*备注:L1.x 显然行不通,但我想实现类似的东西。

4

1 回答 1

4

我认为最简单的方法是Seq.tryPickL1s 上使用,内部函数在 current 的子代中搜索L1

myXml.GetLevel1s()
|> Seq.tryPick (fun L1 ->
    L1.GetLevel2s()
    |> Seq.tryFind (fun L2 -> L2.b = L1.x * L2.a))
|> function
| None -> ""
| Some L2 -> L2.Name
于 2014-02-25T12:41:42.377 回答