Scala:XML空白删除?

时间:2009-11-09 21:22:27

标签: xml scala whitespace

有人知道一个好的scala库可以从XML中删除/压缩空格吗?

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

为:

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

2 个答案:

答案 0 :(得分:62)

scala.xml.Utility.trim()应该做你想做的事:

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>

答案 1 :(得分:2)

无论它值多少,这就是我现在在“自己动手”策略中所做的事情:

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
}