XML processing in Scala part 2

Sun, Nov 10, 2013

Programming Scala #programming #scala

Today we are going to look at some useful XML classes in Scala. These classes can come quite handy when we want to generate XML.

scala.xml.PCData – to generate CDATA section in XML

val someData = new PCData("<code>console.log('unparseText')</code>")
println(someData)
// output : <![CDATA[<code>console.log('unparseText')</code>]]>

scala.xml.Unparsed – to accept unparsed XML

val unparsedText = new Unparsed("<scode>console.log('unparseText')</code></p>")
println(unparsedText)
// output : <scode>console.log('unparseText')</code></p>

 

scala.xml.Text – to implement XML node for text

val text = new Text("<code>console.log('unparseText')</code>")
println(text)
// output : <code>console.log('unparseText')</code>

Bonus

We can define an implicit method to convert String to PCData

implicit class PCDataHelper(val sc: StringContext) extends AnyVal {
    def pcdata(args: Any*): String = {
      //normal string
      val strings = sc.parts.iterator
      
      //expressions in the string
      val expressions = args.iterator
      val buf = new StringBuilder(strings.next)
      
      while(strings.hasNext) {
        buf append expressions.next
        buf append strings.next
      }
      
      new PCData(buf.toString).toString
    }
  }
  println(pcdata"<code>console.log('unparseText')</code>")
  // output : console.log('unparseText')
  // same as the example above