XML, Linq and F#

By Petr at June 27, 2010 01:47
Filed Under:

Here I want to test how to post code snippets to this community. As an example I put here code from “F# Expert” book. I'm using Live Writer with GeSHi plugin for syntax highlighting.

The sample shows how using higher order functions and Linq we can easily and elegantly create XML documents.

F#, using GeSHi 1.0.8.6
  1. open System.Xml.Linq
  2.  
  3. let xml =
  4. "<contacts>
  5. <contact>
  6. <name>John Smith</name>
  7. <phone type=\"home\">+1 626-123-4321</phone>
  8. </contact>
  9. </contacts>"
  10. let doc1 = XDocument.Parse xml
  11.  
  12. let xname n = XName.op_Implicit(n)
  13. let xdoc (el:seq<XElement>) = new XDocument(Array.map box (Array.ofSeq el))
  14. let xelem s el = new XElement(xname s, box el)
  15. let xatt a b = new XAttribute(xname a, b) |> box
  16. let xstr s = box s
  17.  
  18. let doc =
  19. xdoc
  20. [xelem "contacts"
  21. [xelem "contact"
  22. [(xelem "name" (xstr "John Smith"))
  23. (xelem "phone"
  24. [xatt "type" "home"
    xstr "+1 626-123-4321"])
  25. ]
  26. ]
  27.   ]
Parsed in 0.022 seconds at 34.35 KB/s

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading