简体   繁体   中英

Scala - transform a XML literal into a string without newlines

For more clarification in a XML structure I will write every tag in a single line.

Unfortunately the result contains (after transforming to text) more than one line, so the assertion failed. I need the whole result as a single line without newlines

val row = <row>
            <fromSubsystem>02</fromSubsystem>
            <toSubsystem>01</toSubsystem>
            <action>E013</action>
            <comment>return to customer</comment>
          </row>

println("==> " + row.text)  

assert(row.text == "0201E013return to customer")   

==> 
             02
             01
             E013
             return to customer
Exception in thread "main" java.lang.AssertionError: assertion failed
    at scala.Predef$.assert(Predef.scala:146)

Thanks in advance for an elegant solution!

Pongo

row.child.map(_.text.trim).mkString

Why don't you use a regexp?

assert(row.text.replaceAll("\n[ ]+","") == "0201E013") 

//or just "\n +" in replaceAll

If you don't like regexp and dont care about spaces in tag's text you can do something like this:

assert(row.text.filterNot(Set(' ','\n')) == "0201E013") 

将您的断言更改为:

assert(row.text.split('\n').map(_.trim).mkString == "0201E013return to customer")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM