Scala:在 XML 中获取所有叶节点及其路径的最简单方法是什么? [英] Scala: What is the easiest way to get all leaf nodes and their paths in an XML?

查看:107
本文介绍了Scala:在 XML 中获取所有叶节点及其路径的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在实现一个 xml 的 DFS 遍历,以便它转到每个叶节点并生成到叶节点的路径.

I am currently implementing DFS traversal of an xml such that it goes to each leaf node and generates the path to the leaf node.

给定的 XML:

<vehicles>
  <vehicle>
    gg
  </vehicle>
  <variable>
  </variable>
</vehicles>

输出(类似):

Map("gg" -> "vehicles/vehicle", "" -> "vehicles/variable")

如果有一个可用的库可以做到这一点就好了,这样我就不必维护代码了.

谢谢.任何帮助表示赞赏.

It would be great if there is a library available that does this so I dont have to maintain the code.

Thanks. Any help is appreciated.

推荐答案

这里是一个使用标准scala xml库的解决方案,打印出路径图->节点文本"

Here is a solution using standard scala xml library, prints out a map of paths -> "node text"

import scala.xml._               
val x = <div class="content"><a></a><p><q>hello</q></p><r><p>world</p></r><s></s></div>               
var map = Map[String,String]()               
def dfs(n: Seq[Node], brc: String): Unit = 
        n.foreach(x => {
                        if(x.child.isEmpty){
                           if(x.text == ""){ 
                            map = map + (brc + x.label -> "")
                            dfs(x.child,brc)
                          }
                          else{ 
                            map = map + (brc + x.label + " " -> x.text)
                            dfs(x.child,brc)
                          }
                        } 
                        else{ 
                          val bc = brc + x.label + ">"
                          dfs(x.child,bc)
                        }
                     }
               )               

dfs(x,"")
print(map) 

这篇关于Scala:在 XML 中获取所有叶节点及其路径的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆