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

发布于 2024-10-11 05:00:44 字数 790 浏览 3 评论 0原文

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

这很糟糕,因为我想在代码中整齐地列出 XML:

<sample>
  <hello />
</sample>

但是 Scala 认为这与

<sample><hello /></sample>

Proof is in the pudding 的值不同:

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

...给出了什么?

I've discovered that Scala XML literals are sensitive to whitespace, which is kinda strange, isn't it? since XML parsers don't normally give a damn about spaces between the tags.

This is a bummer because I'd like to set out my XML neatly in my code:

<sample>
  <hello />
</sample>

but Scala considers this to be a different value to

<sample><hello /></sample>

Proof is in the pudding:

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

... What gives?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼泪淡了忧伤 2024-10-18 05:00:44

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

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

If you liked it you should have put a trim on it:

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
挽袖吟 2024-10-18 05:00:44

如果要将 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>

If you want to convert the XML literal to a 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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文