val pets =
<Pet>
<Cat>black
<Kitty>small</Kitty>
<Kitty>big</Kitty>
<Kitty>large</Kitty>
</Cat>
<Dog>grey
<Kitty>large</Kitty>
</Dog>
</Pet>
在这里,我需要更改(更新/删除)子节点的<Kitty>{text}</Kitty>
&#34; Cat&#34;在scala中为<baby>{text}</baby>
!
到目前为止,我已尝试过这个,
class xml_class{
def replace(elem:Elem):Elem=elem.copy(
child = elem.child.map{
case elem: Elem if elem.label=="Cat" => <Kitty>{elem}</Kitty>
case elem: Elem => replace(elem)
case other => other
}
)}
var ob =new xml_class()
println(ob.replace(pets))
将输出as,
<Pet>
<Cat>black
<baby>small</baby>
<baby>big</baby>
<baby>large</baby>
</Cat>
<Dog>grey
<baby>large</baby>
</Dog>
</Pet>
因此它实际上更改了<kitty>
中的所有<Cat> & <Dog>
标记,而我只需要根据XPATH条件或{@ p>更改<Cat>
。{/ p>
答案 0 :(得分:0)
如果我的理解是正确的,您需要将Cat
子标签从Kitty
更改为baby
。
class xml_class {
def replace(elem: Elem): Elem = {
elem.copy(child = elem.child.map {
case catEle: Elem if catEle.label == "Cat" =>
catEle.copy(child = catEle.child.map {
case cc: Elem if cc.label == "Kitty" => cc.copy(label = "baby")
case innerOther => innerOther
})
case other => other
})
}
}
输出如下:
<Pet>
<Cat>black
<baby>small</baby>
<baby>big</baby>
<baby>large</baby>
</Cat>
<Dog>grey
<Kitty>large</Kitty>
</Dog>
</Pet>
答案 1 :(得分:0)
scala-xml库有一种定义重写规则的方法:
val kittyToBabyRule = new scala.xml.transform.RewriteRule {
override def transform(n: Node): Seq[Node] = n match {
case <Kitty>{text}</Kitty> => <baby>{text}</baby>
case _ => n
}
}
val kittyTransformer = new scala.xml.transform.RuleTransformer(kittyToBabyRule)
然后您可以在重写规则中使用重写规则:
val catRule = new scala.xml.transform.RewriteRule {
override def transform(n: Node): Seq[Node] = n match {
case e: Elem if e.label == "Cat" => kittyTransformer(n)
case _ => n
}
}
然后,您可以使用顶级规则创建变换器:
val catTransformer = new scala.xml.transform.RuleTransformer(catRule)
然后您可以将变压器运行为:
scala> catTransformer(doc)
res0: scala.xml.Node =
<Pet>
<Cat>black
<baby>small</baby>
<baby>big</baby>
<baby>large</baby>
</Cat>
<Dog>grey
<Kitty>large</Kitty>
</Dog>
</Pet>