Skip to content
August 11, 2008 / edeustace

My first scala function – prefix xml

I’m learning scala in my free time. First thing I’ve done is write a function that prefixes all xml. There is a good chance that there is already another much simpler way of doing this. I just wanted to do it myself as a means of understanding the scala syntax.

If there are better ways to do this I’d love to know.

def prefixElem( prefix : String, elem : Node ) : Node  =
{
  elem match
  {
    case n @ Node(_,_,_,_) =>
    {
      var prefixedElements = for( subNode <- n.child ) yield
      {
        prefixElem( prefix, subNode )
      }
      Elem(prefix, n.label, n.attributes, n.scope, Group( prefixedElements )  )
    }
    case e @ Elem(_,_,_,_,_) =>
    {
      val subElem = prefixElem( prefix, e.child.apply(0))
      Elem(prefix, e.label, e.attributes, e.scope, subElem )
    }
    case other @ _ =>  other
 }
}
//usage

val simpleXml3 =
   <x id="this is an atrribute value">
     <b>hello</b>
     <c id="so is this">
        goodbye
        <d>really</d>
     </c>
   </x>

prefixElem( "ee", simpleXml )

//creates
<ee:x id="this is an atrribute value">
     <ee:b>hello</ee:b>
     <ee:c id="so is this">
          goodbye
          <ee:d>really</ee:d>
     </ee:c>
</ee:x>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: