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