Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append element as child of Anti-XML element

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.

like image 850
Mechanical snail Avatar asked Jun 25 '12 12:06

Mechanical snail


2 Answers

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.

like image 179
Travis Brown Avatar answered Nov 03 '22 17:11

Travis Brown


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.)

like image 3
ncreep Avatar answered Nov 03 '22 16:11

ncreep