How to produce nicely formatted XML in Scala?

Viewed 9474

Say you define the following:

class Person(name: String, age: Int) {
    def toXml =
        <person>
            <name>{ name }</name>
            <age>{ age }</age>
        </person>   
}

val Persons = List(new Person("John", 34), new Person("Bob", 45))

Then generate some XML and save it to a file:

val personsXml = 
    <persons>
        { persons.map(_.toXml) }
    </persons>

scala.xml.XML.save("persons.xml", personsXml)

You end up with the following funny-looking text:

<persons>
        <person>
            <name>John</name>
            <age>32</age>
        </person><person>
            <name>Bob</name>
            <age>43</age>
        </person>
    </persons>

Now, of course, this is perfectly valid XML, but if you want it to be human-editable in a decent text editor, it would be preferable to have it formatted a little more nicely.

By changing indentation on various points of the Scala XML literals - making the code look less nice - it's possible to generate variations of the above output, but it seems impossible to get it quite right. I understand why it becomes formatted this way, but wonder if there are any ways to work around it.

6 Answers

Maybe it will be useful. When you use text editor, try do not put any extra tabs within XML code because they will be saved in xml file.

I mean, your code should look like this:

val personsXml = 
<persons>
   { persons.map(_.toXml) }
</persons>

Instead of this:

val personsXml = 
    <persons>
        { persons.map(_.toXml) }
    </persons>

It perfectly worked for me.

Related