2011-01-08 23 views
14

我發現Scala XML文字對空白很敏感,這有點奇怪,不是嗎?因爲XML解析器通常不會對標籤之間的空間產生任何影響。爲什麼Scala XML文字對標籤之間的空白敏感?

這是一個壞消息,因爲我想整齊地闡述了自己的XML在我的代碼:

<sample> 
    <hello /> 
</sample> 

但斯卡拉認爲這是一個不同的值

<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

因爲空白*是*顯著在XML中 - 它正在變成文本節點。大多數正常的XML處理(例如XPath)只是忽略所有,但是在匹配的節點中選擇(可能的空白)文本。希望有人能提供一個很好的解決方案,以便於處理:p – 2011-01-08 22:15:50

+0

上面的演示:' .child.size` => 1,` .child.size` => 3.這個事實被toString實現隱藏起來。爲什麼要孩子而不是孩子?我不知道... – 2011-01-08 22:21:18

+0

我不知道它是爲空格創建文本節點。有一種澳大利亞古老的口語主義,完美地表達了我的迴應:醃奶奶! – David 2011-01-09 04:13:41

回答

15

如果你喜歡它,你就應該把微調就可以了:

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 
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> 
相關問題