我正在尝试解析 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")