-
Notifications
You must be signed in to change notification settings - Fork 0
/
Xmler.fs
65 lines (55 loc) · 1.77 KB
/
Xmler.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
///
/// Scala-like XML parsing for F#.
///
open System
open System.Xml
open System.IO
open System.Xml.XPath
// Select nodes.
let inline (+/) (nav: XPathNavigator) (path: string) =
let iter = nav.Select(path)
seq { while iter.MoveNext() do yield iter.Current }
// Select a single node.
let inline (+//) (nav: XPathNavigator) (path: string) =
nav.SelectSingleNode(path)
// Get the value of a node.
let inline (+//>) (nav: XPathNavigator) (path: string) =
nav.SelectSingleNode(path).Value
// Get the value of specified attribute for the current node.
let inline (+//>>) (nav: XPathNavigator) (attr: string) =
nav.GetAttribute(attr, String.Empty)
// Some dummy content.
let content = "\
<AddressBook>
<Owner firstName=\"John\" lastName=\"Smith\" />
<Contacts>
<Contact firstName=\"Jane\" lastName=\"Smith\">
<Email>[email protected]</Email>
<Phone type=\"mobile\">617-555-3311</Phone>
</Contact>
<Contact firstName=\"Bob\" lastName=\"Notsmith\">
<Email>[email protected]</Email>
<Phone type=\"office\">716-111-2222</Phone>
</Contact>
</Contacts>
</AddressBook>"
// Something that we can parse into.
type Contact = {
Email : string
Phone : string
PhoneType : string
}
[<EntryPoint>]
let main args =
use stream = new StringReader(content)
let nav = XPathDocument(stream).CreateNavigator()
let firstName = nav +// "/AddressBook/Owner" +//>> "firstName"
let lastName = nav +// "/AddressBook/Owner" +//>> "lastName"
let contacts =
nav +/ "/AddressBook/Contacts/Contact"
|> Seq.map (fun c ->
({ Email = c +//> "Email";
Phone = c +//> "Phone";
PhoneType = c +// "Phone" +//>> "type" }))
|> List.ofSeq
0