Scala:合并数据的 xml 树?
我很好奇组合一组包含类似内容的 xml 树的最佳方法 数据到单个集合(“联合”样式)。
我确实实现了一个可行的解决方案,但代码看起来很糟糕,我有 强烈的直觉,一定有一种更好、更紧凑的方式 实施这一点。
我想做的是在最简单的情况下结合以下内容:
<fruit> <apple /> <orange /> </fruit>
和:
<fruit> <banana /> </fruit>
To:
<fruit> <apple/> <orange/> <banana/> </fruit>
有什么好主意如何在 scala 中干净地实现这个功能吗?
I'm curious for the best way to combine a set of xml trees containing similar
data to a single set ('union' style).
I did implement a working solution but the code looks bad and I have
a strong gut feeling that there must be a much nicer and compact way of
implementing this.
What I'm trying to do is in the simplest case combining something like:
<fruit> <apple /> <orange /> </fruit>
and:
<fruit> <banana /> </fruit>
To:
<fruit> <apple/> <orange/> <banana/> </fruit>
Any good ideas how to make a clean implementation of this in scala?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
但是
这只是
,
从
appleAndOrange
中获取标签
,并忽略banana
中的标签,这里是恰好是一样的。同样,如果它们不相同,您必须决定需要什么检查以及什么行为。前缀、属性和范围也是如此。with
and
you can do
However, this simply takes the the label
<fruit>
fromappleAndOrange
, and ignore the one frombanana
, which here happens to be the same. Same for You have to decide what checks you want and what behavior, if they are not the same. Same for prefixes, attributes, and scopes.这是另一种值得考虑的方法。我们本质上是从字符串构建 scala.xml.Elem 并使用一些 XPath 样式查询。
首先,我们创建了
open
和close
标记,它们只是字符串。然后我们使用一些 XPath 样式查询构造children
。\\
是 Elem 上的一个运算符,它返回 Elem 的元素和所有子序列。\
类似,但它返回 Elem 的元素。“_”
是通配符。为什么不只是
\
?我自己根据文档很难弄清楚这一点,但是查看 XPath for Java 让我相信\\
包含整个 Elem 本身和子元素,而\
仅包含孩子,所以如果我们有 \ "parent"
我们什么也找不到,因为只传递了
。现在这个方法并不牛逼。我们能做些什么来让它变得更棒呢?我们最好利用 Scala 精彩的
Option
类和foldLeft
方法。当然,这还有一个额外的好处,即仅处理一个 Elem(父级不存在的情况)以及作为参数提供的可变数量的 Elem。这是我在提出这个最终方法时运行的一长串示例,
Here is another approach that is worth considering. We're essentially going to be building the scala.xml.Elem from a string and making use of some XPath style querying.
First we created the
open
andclose
tags, which are just strings. Then we constructchildren
by using some XPath style query.\\
is an operator on Elem which returns elements and all subsequences of the Elem.\
is similar but it returns the elements of the Elem."_"
is the wildcard.Why not just
\
? I had trouble figuring this out myself based on the documentation but looking at XPath for Java leads me to believe that\\
includes the entire Elem itself and children while\
only includes the children, so if we had<parent><x/></parent> \ "parent"
we would find nothing since only<x/>
is passed.Now this method is not awesome. What can we do to make it a bit more awesome? We'd better make use of Scala's wonderful
Option
class and thefoldLeft
method.This of course has the sweetly added benefit of working on just one Elem, cases where the parent is not present, and a variable number of Elem provided as arguments. Here is a long list of examples I ran while coming up with this final method,