Reputation: 30647
Suppose I have an XML document stored as an Anti-XML Elem
:
val root : Elem =
<foo attr="val">
<bar/>
</foo>
. I want to append <baz>blahblahblah</baz>
to the root element as a child, giving
val modified_root : Elem =
<foo attr="val">
<bar/>
<baz>blahblahblah</baz>
</foo>
For comparison, in Python you can just root.append(foo)
.
I know I can append (as a sibling) to a Group[Node]
using :+
, but that's not what I want:
<foo attr="val">
<bar/>
</foo>
<baz>blahblahblah</baz>
How do I append it as the last child of <foo>
? Looking at the documentation I see no obvious way.
Similar to Scala XML Building: Adding children to existing Nodes, except this question is for Anti-XML rather than scala.xml
.
Upvotes: 6
Views: 1404
Reputation: 497
Although not yet relevant, but there is an addChild/ren
method on Elem
in master
in the Anti-XML repo.
Its implementation currently contains a bug, but there is an outstanding pull request to fix it.
So you should probably use that in a future release.
(Would've made this a comment, but I'm not yet allowed to do so.)
Upvotes: 3
Reputation: 139028
Elem
is a case class, so you can use copy
:
import com.codecommit.antixml._
val root: Elem = <foo attr="val"><bar/></foo>.convert
val child: Elem = <baz>blahblahblah</baz>.convert
val modified: Elem = root.copy(children = root.children :+ child)
The copy
method is automatically generated for case classes, and it takes named arguments that allow you to change any individual fields of the original instance.
Upvotes: 9