Thursday, December 10, 2009

XML transformations 2

This topic is a continuation of XML Transformations. The previous topic showed a method of creating transformation rules then combining the rules to create a transformation that could be applied to an XML datastructure. This topic takes a different approach of
using a match statement an a recursive method to iterate through the tree.
  1. scala> val xml = <library>
  2.      | <videos>
  3.      | <video type="dvd">Seven</video>
  4.      | <video type="blue-ray">The fifth element</video>
  5.      | <video type="hardcover">Gardens of the moon</video>
  6.      | </videos>
  7.      | <books>
  8.      | <book type="softcover">Memories of Ice</book>
  9.      | </books>
  10.      | </library>
  11. xml: scala.xml.Elem = 
  12. <library>
  13.        <videos>
  14.        <video type="dvd">Seven</video>
  15.        <video type="blue-ray">The fifth element</video>
  16.        <video type="hardcover">Gardens of the moon</video>
  17.        </videos>
  18.        <books>
  19.        <book type="softcover">Memories of Ice</book>
  20.        </books>
  21.        </library>
  22. scala> import scala.xml._
  23. import scala.xml._
  24. scala> def moveElements (node:Node) : Node = node match {
  25.      | case n:Elem if (n.label == "videos") => 
  26.      |   n.copy( child = n.child diff mislabelledBooks)
  27.      | case n:Elem if (n.label == "books") =>
  28.      |   val newBooks = mislabelledBooks map { e => e.asInstanceOf[Elem].copy(label="book") }
  29.      |   n.copy( child = n.child ++ newBooks)
  30.      | case n:Elem => 
  31.      |   val children = n.child map {moveElements _}
  32.      |   n.copy(child = children)
  33.      | case n => n
  34.      | }
  35. moveElements: (node: scala.xml.Node)scala.xml.Node
  36. scala> moveElements(xml)
  37. res1: scala.xml.Node = 
  38. <library>
  39.               <videos>
  40.               <video type="dvd">Seven</video>
  41.               <video type="blue-ray">The fifth element</video>
  42.               
  43.               </videos>
  44.               <books>
  45.               <book type="softcover">Memories of Ice</book>
  46.               <book type="hardcover">Gardens of the moon</book></books>
  47.               </library>

No comments:

Post a Comment