views:

393

answers:

2

Anyone know of a good scala library to do whitespace removal/compaction from XML?

<foo>
  <bar>hello world</bar>
  <baz>  xxx  </baz>
</foo>

to:

<foo><bar>hello world</bar><baz>xxx</baz></foo>

-harryh

+2  A: 

For whatever it's worth, this is what I've got going on now in the "roll my own" strategy:

def compactXml(xml: Node): Node = {
  (xml map {
    case Elem(prefix, label, attributes, scope, children @ _*) => {
      Elem(prefix, label, attributes, scope, children.map(compactXml(_)) :_*)
    }
    case Text(data) => Text(data.trim) 
    case x => x
  }).first
}
harryh
This looks like a good solution. Why do you need a library to do what you are doing in 7 lines?
David Crawshaw
Mainly because I haven't yet convinced myself that my code is 100% correct yet.
harryh
+11  A: 

scala.xml.Utility.trim() should do what you want:

scala> val x = <foo>
     |   <bar>hello world</bar>
     |   <baz>  xxx  </baz>
     | </foo>
x: scala.xml.Elem = 
<foo>
         <bar>hello world</bar>
         <baz>  xxx  </baz>
       </foo>

scala> scala.xml.Utility.trim(x)
res0: scala.xml.Node = <foo><bar>hello world</bar><baz>xxx</baz></foo>
Walter Chang