带有空格的 Scala XML 模式

发布于 2024-12-23 20:30:11 字数 124 浏览 1 评论 0原文

是否存在与以下模式匹配的 xml 值?

xml match { case <foo> { x } </foo> => 42 }

Is there a value of xml which will match the following pattern?

xml match { case <foo> { x } </foo> => 42 }

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

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

发布评论

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

评论(1

橘香 2024-12-30 20:30:11

是的。

scala> val x = 33
x: Int = 33

scala> val xml = <foo> { x } </foo>
xml: scala.xml.Elem = <foo> 33 </foo>

scala> xml match { case <foo> { x } </foo> => 42 }
res0: Int = 42

我认为您的困惑之处在于它与 不匹配。 33

scala> <foo> 33 </foo> match { case <foo> { x } </foo> => 42 }
scala.MatchError: <foo> 33 </foo> (of class scala.xml.Elem)

这是因为当您使用 {} 时,scala 会在 {} 前后的空格中插入额外的元素,因此您得到三个元素,而不是一个。您可以通过调用 unapplySeq (这是用于模式匹配的)来查看这一点:

scala> scala.xml.Elem.unapplySeq(<foo> 33 </foo>)
res4: Option[(String, String, scala.xml.MetaData, scala.xml.NamespaceBinding, Seq[scala.xml.Node])] =
    Some((null,foo,,,ArrayBuffer( 33 )))

scala> scala.xml.Elem.unapplySeq(<foo> { x } </foo>)
res5: Option[(String, String, scala.xml.MetaData, scala.xml.NamespaceBinding, Seq[scala.xml.Node])] =
    Some((null,foo,,,ArrayBuffer( , 33,  )))

请注意,在第二个示例中,您在 ArrayBuffer 中获得了三个元素,而在第一个示例中仅获得了一个元素。所以模式不正确匹配。

Yes.

scala> val x = 33
x: Int = 33

scala> val xml = <foo> { x } </foo>
xml: scala.xml.Elem = <foo> 33 </foo>

scala> xml match { case <foo> { x } </foo> => 42 }
res0: Int = 42

I think where your confusion comes in is it doesn't match against <foo> 33 </foo>

scala> <foo> 33 </foo> match { case <foo> { x } </foo> => 42 }
scala.MatchError: <foo> 33 </foo> (of class scala.xml.Elem)

This is because when you use the {}, scala inserts extra elements for the spaces before and after the {}, so you get three elements, not one. You can see this by calling unapplySeq (which is what is used for the pattern matching):

scala> scala.xml.Elem.unapplySeq(<foo> 33 </foo>)
res4: Option[(String, String, scala.xml.MetaData, scala.xml.NamespaceBinding, Seq[scala.xml.Node])] =
    Some((null,foo,,,ArrayBuffer( 33 )))

scala> scala.xml.Elem.unapplySeq(<foo> { x } </foo>)
res5: Option[(String, String, scala.xml.MetaData, scala.xml.NamespaceBinding, Seq[scala.xml.Node])] =
    Some((null,foo,,,ArrayBuffer( , 33,  )))

Notice in the second example, you're getting three elements in the ArrayBuffer, and only one in the first. So the pattern doesn't match correctly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文