using a match statement an a recursive method to iterate through the tree.
- scala> val xml = <library>
- | <videos>
- | <video type="dvd">Seven</video>
- | <video type="blue-ray">The fifth element</video>
- | <video type="hardcover">Gardens of the moon</video>
- | </videos>
- | <books>
- | <book type="softcover">Memories of Ice</book>
- | </books>
- | </library>
- xml: scala.xml.Elem =
- <library>
- <videos>
- <video type="dvd">Seven</video>
- <video type="blue-ray">The fifth element</video>
- <video type="hardcover">Gardens of the moon</video>
- </videos>
- <books>
- <book type="softcover">Memories of Ice</book>
- </books>
- </library>
- scala> import scala.xml._
- import scala.xml._
- scala> def moveElements (node:Node) : Node = node match {
- | case n:Elem if (n.label == "videos") =>
- | n.copy( child = n.child diff mislabelledBooks)
- | case n:Elem if (n.label == "books") =>
- | val newBooks = mislabelledBooks map { e => e.asInstanceOf[Elem].copy(label="book") }
- | n.copy( child = n.child ++ newBooks)
- | case n:Elem =>
- | val children = n.child map {moveElements _}
- | n.copy(child = children)
- | case n => n
- | }
- moveElements: (node: scala.xml.Node)scala.xml.Node
- scala> moveElements(xml)
- res1: scala.xml.Node =
- <library>
- <videos>
- <video type="dvd">Seven</video>
- <video type="blue-ray">The fifth element</video>
-
- </videos>
- <books>
- <book type="softcover">Memories of Ice</book>
- <book type="hardcover">Gardens of the moon</book></books>
- </library>
No comments:
Post a Comment