Add Element as a Child 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 add <baz>blahblahblah</baz> to the root as a child, specifying

 val modified_root : Elem = <foo attr="val"> <bar/> <baz>blahblahblah</baz> </foo> 

For comparison, in Python you can just root.append(foo) .

I know that I can add (as a native) to Group[Node] with :+ , but this is not what I want:

 <foo attr="val"> <bar/> </foo> <baz>blahblahblah</baz> 

How to add it as the last child <foo> ? Looking at the documentation , I see no obvious way.


Like Scala XML Creation: Adding children to existing nodes , except this question is for anti-XML, not scala.xml .

+6
source share
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 the case classes , and it takes named arguments that allow you to modify any individual fields in the source instance.

+9
source

Although this is not yet relevant, there is an addChild/ren method on Elem in master in the Anti-XML repository. Its implementation currently contains an error, but there is a wonderful retrieval request to fix this. Therefore, you should probably use this in a future version.

(I would make a comment, but I am not yet allowed to do this.)

+3
source

Source: https://habr.com/ru/post/918936/


All Articles