Friday, August 7, 2009

Creating XML

Scala allows you to embed XML directly into a program and provides several ways to manipulate it. Today we will look at writing XML.
  1. scala>val xml = <root>
  2.      | <child>text</child>
  3.      | </root>
  4. xml: scala.xml.Elem =
  5. <root>
  6.        <child>text</child>
  7.        </root>
  8. scala>val data = "a string"
  9. data: java.lang.String = a string
  10. // you can embed logic and variables in the xml by surrounding with {}
  11. scala>val xml = <root>{data}</root>
  12. xml: scala.xml.Elem = <root>a string</root>
  13. scala>val xml = <root>{ for( i <- 1 to 3 ) yield {<xml i={i.toString}/>} } </root>
  14. xml: scala.xml.Elem = <root><xml i="1"></xml><xml i="2"></xml><xml i="3"></xml></root>
  15. scala>val xml = <root>{ for( i <- 1 to 3 ) yield<child>{i}</child> } </root>
  16. xml: scala.xml.Elem = <root><child>1</child><child>2</child><child>3</child></root>
  17. // save xml to file.  Note Scala 2.8 is changin save API
  18. // and will require the encoding and DocType information
  19. scala> scala.xml.XML.save( "/tmp/doc.xml", xml)

No comments:

Post a Comment