为什么Scala XML文字对标记之间的空格敏感?

时间:2011-01-08 20:53:04

标签: xml scala

我发现Scala XML文字对空白很敏感,这有点奇怪,不是吗?因为XML解析器通常不会对标签之间的空格感到遗憾。

这是一个无赖,因为我想在我的代码中整齐地列出我的XML:

<sample>
  <hello />
</sample>

但Scala认为这是与

不同的值
<sample><hello /></sample>

证明在布丁中:

scala> val xml1 = <sample><hello /></sample>
xml1: scala.xml.Elem = <sample><hello></hello></sample>

scala> val xml2 = <sample>
     | <hello />
     | </sample>
xml2: scala.xml.Elem = 
<sample>
<hello></hello>
</sample>

scala> xml1 == <sample><hello /></sample>
res0: Boolean = true

scala> xml1 == xml2
res1: Boolean = false

......什么给出了?

2 个答案:

答案 0 :(得分:16)

如果你喜欢它,你应该修剪它:

scala> val xml1 = <sample><hello /></sample>
xml1: scala.xml.Elem = <sample><hello></hello></sample>

scala> val xml2 = <sample>
     | <hello />
     | </sample>
xml2: scala.xml.Elem = 
<sample>
<hello></hello>
</sample>

scala> xml1 == xml2
res14: Boolean = false

scala> xml.Utility.trim(xml1) == xml.Utility.trim(xml2)
res15: Boolean = true

答案 1 :(得分:0)

如果要将XML文字转换为StringBuilder

scala> val xml1 = <sample><hello /></sample>
xml1: scala.xml.Elem = <sample><hello></hello></sample>

scala> xml.Utility.toXML(xml1, minimizeTags=true)
res2: StringBuilder = <sample><hello /></sample>