本文介绍了scala:将属性(奇数行和偶数行)添加到xml表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Lift应用程序中,我想添加一个特殊的标签,该标签将下一张表的,递归就会提前停止.如果没有,我们可能会遇到问题...

The problem with RewriteRules seems to be that they nest too deeply. That is, once a rule for adding attributes to <tr> is started, it is not possible to stop it. (At least, it did not work for me.) However, I have found a recursive solution which works for me. Also, as long as there is a <tbody> inside, the recursion will stop early. If there isn’t, we might have a problem…

abstract class Loop {
    val stream_iter = Stream.continually(elems.toStream).flatten.iterator
    def next = stream_iter.next
    def elems: Seq[String]
}
class Cycle extends Loop { override def elems = List("odd", "even") }

// Call this when in <tbody>
def transformChildren(sn: Seq[Node]): Seq[Node] = {
    // Start a new cycle
    val cycle = new Cycle
    sn.map{ node => node match {
        case Elem(prefix, "tr", att, scope, ch @ _*) =>
            Elem(prefix, "tr", att, scope, ch:_*) % Attribute(None, "class", Text(
                List(att.get("class").getOrElse("").toString, cycle.next).reduceLeft(_+" "+_).trim
                ), Null)
        case other => other
        }
    }
}

// Look for first <tbody>, transform child tr elements and stop recursion
// If no <tbody> found, recurse
def recurse(sn: NodeSeq): NodeSeq = sn.map{ node =>
    node match {
        case Elem(prefix, "tbody", att, scope, ch @ _*)
            => Elem(prefix, "tbody", att, scope, transformChildren(ch):_*)
        case Elem(prefix, label, att, scope, ch @ _*)
            => Elem(prefix, label, att, scope, recurse(ch):_*)
        case other => other
    }
}

val code = <table>
  <thead><tr><td>Don’t</td><td>transform this</td></tr></thead>
  <tbody>
    <tr class="otherclass">
      <td>r1c1</td><td>r1c2</td>
    </tr>
    <tr>
      <td><table><tbody><tr><td>Neither this.</td></tr></tbody></table></td><td>r2c2</td>
    </tr>
    <tr>
      <td>r3c1</td><td>r3c2</td>
    </tr>
  </tbody>
</table>

println(recurse(code))

赠予:

<table>
  <thead><tr><td>Don’t</td><td>transform this</td></tr></thead>
  <tbody>
    <tr class="otherclass odd">
      <td>r1c1</td><td>r1c2</td>
    </tr>
    <tr class="even">
      <td><table><tbody><tr><td>Neither this</td></tr></tbody></table></td><td>r2c2</td>
    </tr>
    <tr class="odd">
      <td>r3c1</td><td>r3c2</td>
    </tr>
  </tbody>
</table>

这篇关于scala:将属性(奇数行和偶数行)添加到xml表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 20:00