tags:

views:

1338

answers:

2

How can i use linq to xml in F# to extract all specific tags from an XML file.

Open the file

let Bookmarks(xmlFile:string) = 
    let xml = XDocument.Load(xmlFile)

Once i have the XDocument how can I navigate it using Linq to XML?

can someone point me in the right direction ?

Edit: Part of my solution

let xname (tag:string) = XName.Get(tag)
let tagUrl (tag:XElement) = let attribute = tag.Attribute(xname "href")
                            attribute.Value
let Bookmarks(xmlFile:string) = 
    let xml = XDocument.Load(xmlFile)
    xml.Elements <| xname "A" |> Seq.map(tagUrl)
+1  A: 

Caveat: I've never done linq-to-xml before, but looking through other posts on the topic, this snippet has some F# code that compiles and does something, and thus it may help you get started:

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

let xmlStr = @"<?xml version='1.0' encoding='UTF-8'?>
<doc>
    <blah>Blah</blah>
    <a href='urn:foo' />
    <yadda>
        <blah>Blah</blah>
        <a href='urn:bar' />
    </yadda>
</doc>"

let xns = XNamespace.op_Implicit ""
let a = xns + "a"
let reader = new StringReader(xmlStr)
let xdoc = XDocument.Load(reader)
let aElements = [for x in xdoc.Root.Elements() do
                 if x.Name = a then
                     yield x]
let href = xns + "href"
aElements |> List.iter (fun e -> printfn "%A" (e.Attribute(href)))
Brian
+5  A: 
#light
open System
open System.Xml.Linq

let xname s = XName.Get(s)
let bookmarks (xmlFile : string) = 
    let xd = XDocument.Load xmlFile
    xd.Descendants <| xname "bookmark"

This will find all the descendant elements of "bookmark". If you only want direct descendants, use the Elements method (xd.Root.Elements <| xname "whatever").

MichaelGG