Search code examples
scalascala-xml

Scala XML extract the element in comma separator


My Code

scala.xml.XML.loadString("<?xml version='1.0' encoding='utf-8'?>" + line(1)).child

It will give me the list like this:

List(<c2>KH0011201</c2>, <c3>-1</c3>, <c4>380</c4>, <c7>50000</c7>, <c98/>)

I want to be like this

KH0011201, -1, 380, 50000, null

I have tried with:

scala.xml.XML.loadString("<?xml version='1.0' encoding='utf-8'?>" + line(1)).child.text

but it gives me the line, cannot identified.


Solution

  • The xml.Elem::text method you've tried to use is indeed the right method to call, but you have to apply it on each child within a map transformation:

    import scala.xml.Elem
    
    List[Elem](<c2>KH0011201</c2>, <c3>-1</c3>, <c4>380</c4>, <c7>50000</c7>, <c98/>)
      .map(_.text)
    // List[String] = List("KH0011201", "-1", "380", "50000", "")
    

    Note that it transforms the value of the empty <c98/> element to "" and not null.