12

Specifically, what's the easiest and most idiomatic way to replace special XML characters in a string. E.g., what's the easiest and most idiomatic way to convert <Jack & Jill> to &lt;Jack &amp; Jill&gt;.

4 Answers 4

28

Turns out there is an easy way to do this (despite a quick web-search not revealing an obvious solution): just use method xml.Utility.escape.

Sign up to request clarification or add additional context in comments.

1 Comment

xml.Utility.escape does not escape e.g. « &laquo; see my answer proposal
2

If you are looking to escape the @ sign in a scala.html file, for instance, using Scala/Play, do @@.

And give the person who provided this answer here How to print @ symbol in HTML with play framework (scala) an upvote.

I came across this page while looking for the above answer, so I just wanted to duplicate it here since other people may end up here as well.

Comments

1

I propose using the function org.apache.commons.text.StringEscapeUtils.escapeHtml4, added into build.sbt by libraryDependencies += "org.apache.commons" % "commons-text" % "1.9"

( xml.Utility.escape does not escape e.g. « &laquo; )

1 Comment

This is helpful; I've noticed xml.Utility.escape does not support anything beyond the default XML entities.
0

Using scala-xml you can create a scala.xml.Text node and print content using toString:

println(scala.xml.Text("<Jack & Jill>").toString)

This will show:

&lt;Jack &amp; Jill&gt;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.