2

我正在尝试解析 XML 文件的目录,然后在存在给定节点的情况下选择特定属性的值。我无法理解以下 F# 导致的编译错误的原因。

open System
open System.IO
open System.Xml
open System.Xml.XPath
open System.Xml.Linq


let configRootDirectory = @"C:\dir"
let relativeProductDir = @"relDir"

let ExtractConfiguredCalculator (productConfigFile:string) = 
    let xmlNavigator = XPathDocument(productConfigFile).CreateNavigator()
    let node = xmlNavigator.SelectSingleNode(@"Product/SupportedRisk/Risk[@type='PV']") 
    node.GetAttribute("methodology", "")

let configFile = Directory.GetFiles(Path.Combine(configRootDirectory, relativeProductDir), @"*.xml")
                    |> Seq.cast<string>
                    |> Seq.iter(fun configFileName -> ExtractConfiguredCalculator(configFileName))                  
                    |> Seq.filter(fun configuredCalculatorNode -> configuredCalculatorNode != null)
                    |> Seq.iter(fun calculator -> Console.WriteLine(calculator))

上面的代码片段来自我在 LinqPad 中试验的代码。看到的错误信息如下。

This expression was expected to have type     unit     but here has type     string   

更新 试图获得更多 f#-ish。请建议是否可以改进。

let configFile = 
        Directory.GetFiles(Path.Combine(configRootDirectory, relativeProductDir), @"*.xml")    
        |> Seq.map(fun configFileName -> 
                    let xmlNavigator = XPathDocument(configFileName).CreateNavigator()
                    let node = xmlNavigator.SelectSingleNode(@"Product/SupportedRisk/Risk[@type='PV']")
                    match node with
                    | null -> "PV not configured"
                    | _ -> 
                        let attributeValue = node.GetAttribute("methodology", "")
                        match attributeValue with 
                        | null -> "Calculator not configured"
                        | _ -> attributeValue)
        |> Seq.iter (printfn "%s")
4

2 回答 2

6

您必须将第一个更改Seq.iterSeq.map返回后续所需的序列Seq.filter

不过我有几条评论:

  • Seq.cast是多余的,因为Directory.GetFiles返回string []
  • 当你有Seq.mapSeq.filter在一起时,你总是可以用Seq.choose.
  • printfn是一种比Console.WriteLine.

这是一个改进的版本:

let configFile = 
        Directory.GetFiles(Path.Combine(configRootDirectory, relativeProductDir), @"*.xml")    
        |> Seq.choose (fun configFileName -> 
                            let config = ExtractConfiguredCalculator(configFileName)
                            if config <> null then Some config else None)
        |> Seq.iter (printfn "%s")
于 2012-07-10T16:52:47.497 回答
4

你的第一个电话Seq.iter应该是 to Seq.mapExtractConfiguredCalculator返回stringSeq.iter期望函数返回unit.

于 2012-07-10T16:52:20.297 回答