简体   繁体   中英

Writing List[Node] to an xml file in scala

I am tring to write a list of Node (xml's node) to xml file.

By writing:

 val xml = <x>{nodes}</x>

where nodes are the list of nodes- I am getting all the nodes in one line .

What can I do to print every node in a new line?

Here's the answer. In short, you can scala.xml.PrettyPrinter for your purposes. You should also remember (you probably do) that these classes are shipped in a separate library as of 2.11 release.

Eg:

scala> val printer = new scala.xml.PrettyPrinter(80, 2)

scala> val nodes = List(
           <lol>node level 1</lol>, 
           <bar><foo>node level 2</foo></bar>
       )

scala> printer.formatNodes(nodes)
res1: String =
<lol>node level 1</lol><bar>
  <foo>node level 2</foo>
</bar>

Actually, when I look at the result, I see that it differs somewhat from the desired output. I'd recommend using a little bit longer, but more matching to your expectations, variant:

nodes.map(node => printer.format(node)).mkString("\n")

That will separate each node by \\n :

<lol>node level 1</lol>
<bar>
  <foo>node level 2</foo>
</bar>

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