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;.

Chris W.
  • 1,680
  • 16
  • 35

3 Answers3

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.

Chris W.
  • 1,680
  • 16
  • 35
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.

Community
  • 1
  • 1
DowntownDev
  • 842
  • 10
  • 15
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; )

Hartmut Pfarr
  • 5,534
  • 5
  • 36
  • 42
  • 1
    This is helpful; I've noticed `xml.Utility.escape` does not support anything beyond the default XML entities. – Chris W. Jul 11 '22 at 15:47