scala中的递归XML

Fel*_*lix 7 xml scala recursive-query

我试图用scala解析这个文件:

<?xml version="1.0"?>
<model>
    <joint name="pelvis">
            <joint name="lleg">
                    <joint name="lfoot"/>
            </joint>
            <joint name="rleg">
                    <joint name="rfoot"/>
            </joint>
    </joint>
</model>
Run Code Online (Sandbox Code Playgroud)

我想用它为我的2D动画引擎创建一个骨架.应将每个关节制成相应的对象,并将所有儿童加入其中.

所以这部分应该产生类似于这样的结果:

j = new Joint("pelvis")
lleg = new Joint("lleg")
lfoot = new Joint("lfoot")
rleg = new Joint("rleg")
rfoot = new Joint("rfoot")
lleg.addJoint(lfoot)
rleg.addJoint(rfoot)
j.addJoint(lleg)
j.addJoint(rleg)
Run Code Online (Sandbox Code Playgroud)

但是,我无法浏览xml代码.首先,我不确定我是否完全理解语法 xml \\ "joint",这似乎产生了包含所有标签的NodeSeq.


主要问题:

  1. 在scala中使用xml理解语法的问题,即 xml \\ "...", Elem.child?,
  2. 从父节点获取属性而不从所有子节点获取属性的问题(xml \\ "@attribute"生成所有属性的连接..?)

Dan*_*ral 6

运算符\\是类似XPath的运算符.它将"选择"具有某种特征的所有后代.

这可以在两个通道中完成,如下所示:

val jointSeq = xml \\ "joint"
val jointMap = scala.collection.mutable.Map[String, Joint]

// First pass, create all joints
for {
  joint <- jointSeq
  names <- joint attribute "name"
  name <- names
} jointMap(name) = new Joint(name)

// Second pass, assign children
for {
  joint <- jointSeq
  names <- joint attribute "name"
  name <- names
  child <- joint \ "joint" // all direct descendants "joint" tags
  childNames <- child attribute "name"
  childName <- childNames
} jointMap(name).addJoint(jointMap(childName))
Run Code Online (Sandbox Code Playgroud)

我想我更喜欢递归解决方案,但这应该是可行的.