scala - XML 插入/更新 [英] scala - XML insert/update
本文介绍了scala - XML 插入/更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你知道根据 XPath 插入和(或)更新节点的任何 Scala API 吗?例如,对于给定的节点和 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
谢谢
推荐答案
你可以使用 RewriteRule
来做到这一点,2.10.3 文档.
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屋!
查看全文