XML flatten to separate Columns

Hi,
how can i bring this XML-Part (Sorry, I cannot Insert a XML-Script into this Window :thinking:)

image

to a output like this, with separatet columns in Scala

    GradeId;check,screen
    14BB;14BB.00.0001;Accumulation
    14DD;14DD.05.0001;Accumulation
    14AA;14AA.00.0001;Accumulation

Thanks and Regards
Nicole
Merry Christmas :blush:

You can use the XML parser from Scala’s standard library (which is not included since 2.11, but can be added with this sbt dependency: “org.scala-lang.modules” %% “scala-xml” % “1.1.1”).

val color = XML.loadFile("color.xml")          // load the xml file
val attrs = List("GradeId", "check", "screen") // which attributes to use as columns
val attributeLists: Seq[List[String]] = for {
  elem <- doc \ "ColorGrade"                   // use \ to navigate xml nodes
} yield attrs.map(attr =>
    elem.attribute(attr).map(_.text).getOrElse("")  // get attribute contents
)

val csv = attrs.mkString(";") + "\n" +                  // add header
    attributeLists.map(_.mkString(";")).mkString("\n")  // join attributes, then lines

If your xml snippet is part of a larger document, you’ll have to adjust the path in line 4. See the tutorial for scala-xml for some ways to navigate XML structure.

PS: to add code snippets like xml, use three backticks ( ``` ) so it won’t be removed :wink:

1 Like