escapechars.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2016 Charles Banning. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file
  4. package mxj
  5. import (
  6. "bytes"
  7. )
  8. var xmlEscapeChars bool
  9. // XMLEscapeChars(true) forces escaping invalid characters in attribute and element values.
  10. // NOTE: this is brute force with NO interrogation of '&' being escaped already; if it is
  11. // then '&' will be re-escaped as '&'.
  12. //
  13. /*
  14. The values are:
  15. " "
  16. ' '
  17. < &lt;
  18. > &gt;
  19. & &amp;
  20. */
  21. func XMLEscapeChars(b bool) {
  22. xmlEscapeChars = b
  23. }
  24. // Scan for '&' first, since 's' may contain "&amp;" that is parsed to "&amp;amp;"
  25. // - or "&lt;" that is parsed to "&amp;lt;".
  26. var escapechars = [][2][]byte{
  27. {[]byte(`&`), []byte(`&amp;`)},
  28. {[]byte(`<`), []byte(`&lt;`)},
  29. {[]byte(`>`), []byte(`&gt;`)},
  30. {[]byte(`"`), []byte(`&quot;`)},
  31. {[]byte(`'`), []byte(`&apos;`)},
  32. }
  33. func escapeChars(s string) string {
  34. if len(s) == 0 {
  35. return s
  36. }
  37. b := []byte(s)
  38. for _, v := range escapechars {
  39. n := bytes.Count(b, v[0])
  40. if n == 0 {
  41. continue
  42. }
  43. b = bytes.Replace(b, v[0], v[1], n)
  44. }
  45. return string(b)
  46. }