import scala.xml._
import scala.xml.transform.{RewriteRule, RuleTransformer}
object TransformIssue {
def addNewElement(): RewriteRule = new RewriteRule {
override def transform(n: Node): Seq[Node] = n match {
case <element></element> => <element><new></new></element>
}
}
def addThingElement(): RewriteRule = new RewriteRule {
override def transform(n: Node): Seq[Node] = n match {
case <element>{ children@_*}</element> => <element>{ children }</element>
case <new></new> => <new><thing></thing></new>
}
}
def change(node: Node): Node =
new RuleTransformer(
addNewElement(),
addThingElement()
).transform(node).head
def changeWorkaround(node: Node): Node = {
val out1 = new RuleTransformer(
addNewElement()
).transform(node).head
new RuleTransformer(
addThingElement()
).transform(out1).head
}
}
--
import org.scalatest.{FlatSpec, FunSpec}
import org.scalatest._
class TransformIssueSpec extends FlatSpec with Matchers {
it should "apply transform to created elements" in {
val output = TransformIssue.change(<element></element>)
output should be(<element><new><thing></thing></new></element>)
} // fails
it should "work the same as the workaround imo" in {
TransformIssue.change(<element></element>) should equal(TransformIssue.changeWorkaround(<element></element>))
} // fails
}
当我们使用两个重写规则应用变换时:第一个添加新元素,第二个将子元素添加到新元素;那么第二个重写规则与第一个规则中添加的元素不匹配。
当我们在两个单独的 RuleTransformer 中应用相同的 RewriteRules 时,它确实会将子代添加到第一步中添加的元素中。我们希望change
和changeWorkaround
函数产生相同的输出。