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
.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With