Archive

Posts Tagged ‘tags’

Removing empty XML elements in Scala

March 21, 2011 1 comment
import xml.transform.{RuleTransformer, RewriteRule}
import xml.{NodeSeq, Node, Elem}
import xml.Utility.trim

object RemoveEmptyElementsSpike {
  val x1 = <xml><empty/><nonEmpty>data</nonEmpty></xml>
  val x2 = <xml><nonEmpty name="legend"></nonEmpty><empty /></xml>
  val x3 = <xml><Empty><empty/></Empty><nonEmpty>data</nonEmpty></xml>
  val x4 = <xml><empty>
           </empty><nonEmpty>data</nonEmpty></xml>
  val x5 = <xml><empty c={val s:String=null;s}/><nonEmpty name="f"/></xml>

  class RemoveEmptyTagsRule extends RewriteRule {
      override def transform(n: Node) = n match {
          case e @ Elem(prefix, label, attributes, scope, child @ _*) if
              (isEmptyElement(e)) => NodeSeq.Empty
          case other => other
      }
  }

  val myRule = new RuleTransformer(new RemoveEmptyTagsRule)

  private def isEmptyElement(n: Node): Boolean = n match {
      case e @ Elem(prefix, label, attributes, scope, child @ _*) if
          (e.text.isEmpty &&
            (e.attributes.isEmpty || e.attributes.forall(_.value == null))
           && e.child.isEmpty) => true
      case other => false
  }

  def main(args: Array[String]) = {
      println(myRule.transform(trim(x1)))
      println(myRule.transform(trim(x2)))
      println(myRule.transform(trim(x3)))
      println(myRule.transform(trim(x4)))
      println(myRule.transform(trim(x5)))
  }
}

/* Output
<xml><nonEmpty>data</nonEmpty></xml>
<xml><nonEmpty name="legend"></nonEmpty></xml>
<xml><nonEmpty>data</nonEmpty></xml>
<xml><nonEmpty>data</nonEmpty></xml>
<xml><nonEmpty name="f"></nonEmpty></xml>
*/