I am learning F# and I trying to write a simple XML parser. In C#, I can easily use the + operator to combine a namespace and name, but not in F#. I am getting the following error on the last line of the code below:
Error 1 Type constraint mismatch. The type
XName
is not compatible with type
string
The type 'XName' is not compatible with the type 'string'
This is the code. The compiler doesn't like the "ns + d".
let parse(pageResult: DownloadPageResult) =
if pageResult.ErrorOccured then 0
else
let reader = new StringReader(pageResult.Source)
let doc = XDocument.Load(reader)
let ns = XNamespace.Get("a")
let d = XName.Get("entry")
doc.Elements(ns + d) |> Seq.length
Any idea why I am seeing this? Thanks!
The XNamespace.Addition operator takes an XNamespace
and a string
. The compiler is complaining because you're attempting to pass an XName
-typed variable (d
) where it expects a string
.
It should work if you change your last line to:
doc.Elements(ns + d.LocalName) |> Seq.length
Or, as Tomas points out, you don't even need to create the d
variable, you can just use the name directly, like this:
doc.Elements(ns + "entry") |> Seq.length