harryh
harryh

Reputation: 643

Scala: XML Whitespace Removal?

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>

Upvotes: 44

Views: 7075

Answers (2)

Walter Chang
Walter Chang

Reputation: 11606

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>

Upvotes: 69

harryh
harryh

Reputation: 643

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
}

Upvotes: 2

Related Questions