xmlscalaanti-xml

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.


Solution

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