DEV Community

David Geirola
David Geirola

Posted on • Updated on

Edit XML in Scala in a FP way

Hi guys , i'm new here and this in my first post!

I'm here because i'd like to share with you a small project i realized for my company due the difficulties and boilerplates found using Scala XML library's API.

I hope that someone can contribute to it.

Github: https://github.com/geirolz/advxml

Features:

  • Append, Remove, Replace XML nodes
  • Edit node's attributes
  • Read XML handling optionality and mandatory nodes and attributes
  • Convert XML into Object and viceversa
  • Normalize XML
  • Convert Java Document to Scala NodeSeq

Example:

import com.github.geirolz.advxml.all._
import scala.xml._
import scala.util._


//import MonadError instance for Try
import cats.instances.try_._

val doc: Elem =
<Persons>
 <Person Name="Mimmo">
  <Cars>
   <Car Brand="Fiat"/>
  </Cars>
 </Person>
</Persons>


val rule = $(_ \ "Person" \ "Cars")
 ==> Append(<Car Brand="Lamborghini"/>)
 ==> Append(<Car Brand="Ferrari"/>)
 ==> Append(<Car Brand="Bmw"/>)


val result: Try[NodeSeq] = doc.transform[Try](rule)
Enter fullscreen mode Exit fullscreen mode

I hope this small project can help someone in desperation with Scala XML library

Let me know what you think about it :)

Top comments (0)