I Have an XML Node that I want to add children to over time:
val root: Node =
But I cannot see methods such as
Well start with this:
def addChild(n: Node, newChild: Node) = n match {
case Elem(prefix, label, attribs, scope, child @ _*) =>
Elem(prefix, label, attribs, scope, child ++ newChild : _*)
case _ => error("Can only add children to elements!")
}
The method ++
works here because child
is a Seq[Node]
, and newChild
is a Node
, which extends NodeSeq
, which extends Seq[Node]
.
Now, this doesn't change anything, because XML in Scala is immutable. It will produce a new node, with the required changes. The only cost is that of creating a new Elem
object, as well as creating a new Seq
of children. The children node, themselves, are not copied, just referred to, which doesn't cause problems because they are immutable.
However, if you are adding children to a node way down on the XML hierarchy, things get complicated. One way would be to use zippers, such as described in this blog.
You can, however, use scala.xml.transform
, with a rule that will change a specific node to add the new child. First, write a new transformer class:
class AddChildrenTo(label: String, newChild: Node) extends RewriteRule {
override def transform(n: Node) = n match {
case n @ Elem(_, `label`, _, _, _*) => addChild(n, newChild)
case other => other
}
}
Then, use it like this:
val newXML = new RuleTransformer(new AddChildrenTo(parentName, newChild)).transform(oldXML).head
On Scala 2.7, replace head
with first
.
Example on Scala 2.7:
scala> val oldXML =
oldXML: scala.xml.Elem =
scala> val parentName = "parent"
parentName: java.lang.String = parent
scala> val newChild =
newChild: scala.xml.Elem =
scala> val newXML = new RuleTransformer(new AddChildrenTo(parentName, newChild)).transform(oldXML).first
newXML: scala.xml.Node =
You could make it more complex to get the right element, if just the parent isn't enough. However, if you need to add the child to a parent with a common name of a specific index, then you probably need to go the way of zippers.
For instance, if you have
, and you want to add
to the second, that would be difficult to do with rule transformer. You'd need a RewriteRule against books
, which would then get its child
(which really should have been named children
), find the nth book
in them, add the new child to that, and then recompose the children and build the new node. Doable, but zippers might be easier if you have to do that too much.