scala-XML插入/更新 [英] scala - XML insert/update
本文介绍了scala-XML插入/更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您是否知道要根据XPath插入和(或)更新节点的任何Scala API?例如,对于给定的Node和XPath,此API会使用新节点创建XML副本
do you know any Scala API to insert and (or) update Nodes according to XPath? e.g for a given Node and XPath, this API would create a copy of XML with new node
谢谢
推荐答案
You can use the RewriteRule
to do this, 2.10.3 documentation.
val cats = <Cats>
<Cat Name="Floyd"/>
<Cat Name="Onyx"/>
</Cats>
然后假设RewriteRule
class AddCat(name: String) extends RewriteRule {
override def transform(n: Node): Seq[Node] = n match {
case e: Elem if e.label == "Cats" =>
val cats = (e \\ "Cat")
val newCat = <Cat Name={name}/>
new Elem(e.prefix, "Cats", e.attributes, e.scope, e.minimizeEmpty, (cats ++ newCat).toSeq:_*)
case x => x
}
}
那你就可以做
val rule = new RuleTransformer(new AddCat("Stevie"))
rule.transform(cats)
res2: Seq[scala.xml.Node] = List(<Cats><Cat Name="Floyd"/><Cat Name="Onyx"/><Cat Name="Stevie"/></Cats>)
类似地,如果您想更改属性
Similarly if you wanted to change an attribute
class AddLastName(name: String, lastName: String) extends RewriteRule {
override def transform(n: Node): Seq[Node] = n match {
case e: Elem if e.label == "Cat" && (e \\ "@Name" text).equals(name) =>
val cat: String = e.attributes("Name").head.text
e % Attribute(None, "Name", Text(s"$name $lastName"), Null)
case x => x
}
}
val rule = new RuleTransformer(new AddLastName("Stevie", "Nicks"))
rule.transform(cats)
res3: Seq[scala.xml.Node] = List(<Cats><Cat Name="Floyd"/><Cat Name="Onyx"/><Cat Name="Stevie Nicks"/></Cats>)
这两种方法都能满足您的需求.困难的部分是弄清楚如何到达子节点,然后建立父节点.
Both of these approaches would do what you're looking for. The hard part is figuring out how to get at the children, then build the parent node.
这篇关于scala-XML插入/更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文