Search code examples
scalascala-xml

append xml node if it not present in the list


I have block of code:

object XmlExample {

  def main(args: Array[String]): Unit = {
    val someXml = 
     <books>
      <book title="The Woman in White">
        <author>Wilkie Collins</author>
      </book> <book title="Great Expectations">
        <author>Charles Dickens</author>
      </book>
    </books>
    println("The xml object is of type: " + someXml.child)


  }

}

I want check if node <c1>does not exist as its child, then I added it like <c1>Null</c1>


Solution

  • I'm not sure to have fully understood does not exist as its child ... or what you exactly mean by I added it but here's my straight answer for adding optionally a direct child of books :

    def addC1IfNotHere(someXml: scala.xml.Elem) = (someXml \ "c1") match {
      case Seq() =>
        someXml.copy(child = <c1>Null</c1> +: someXml.child)
      case _ => someXml
    }
    

    this works like:

    val someXmlWithC1 = 
    <books>
       <c1>anything else</c1>
       <book title="The Woman in White">
        <author>Wilkie Collins</author>
       </book> <book title="Great Expectations">
        <author>Charles Dickens</author>
      </book>
    </books>
    val someXmlWithoutC1 = 
    <books>
       <book title="The Woman in White">
        <author>Wilkie Collins</author>
       </book> <book title="Great Expectations">
        <author>Charles Dickens</author>
      </book>
    </books>
    val hasItsOriginalC1 = addC1IfNotHere(someXmlWithC1)
    val hasANewC1 = addC1IfNotHere(someXmlWithoutC1)
    println(hasItsOriginalC1)
    println(hasANewC1)
    

    should normally print:

    <books>
       <c1>anything else</c1>
       <book title="The Woman in White">
        <author>Wilkie Collins</author>
       </book> <book title="Great Expectations">
        <author>Charles Dickens</author>
      </book>
    </books>
    <books><c1>Null</c1>
       <book title="The Woman in White">
        <author>Wilkie Collins</author>
       </book> <book title="Great Expectations">
        <author>Charles Dickens</author>
      </book>
    </books>
    

    Hope it helps. Don't hesitate whenever c1 isn't at the place you expected or something else.