Scala XML Building: Adding children to existing Nodes

前端 未结 9 1262
感动是毒
感动是毒 2020-12-15 04:42

I Have an XML Node that I want to add children to over time:

val root: Node = 

But I cannot see methods such as

9条回答
  •  感动是毒
    2020-12-15 05:37

    your root definition is actually an Elem object, a subclass of node, so if you drop your unnecessary Node typing (which hides its implementation) you could actually do a ++ on it since the Elem class has this method.

    val root = 
    val myChild = 
    root.copy(child = root.child ++ myChild)
    

    scala ev:

    root: scala.xml.Elem = 
    myChild: scala.xml.Elem = 
    res2: scala.xml.Elem = 
    

    Since every Elem and every Node is a NodeSeq you can add these pretty effectively even if what you are appending is an unknown sequence:

    val root = 
    //some node sequence of unknown subtype or structure
    val children: scala.xml.NodeSeq =  
    root.copy(child = root.child ++ children)
    

    scala ev:

    root: scala.xml.Elem = 
    children: scala.xml.NodeSeq = NodeSeq(, )
    res6: scala.xml.Elem = 
    

提交回复
热议问题