Skip to content

Commit

Permalink
fix(encoding/gxml): XML special character encoding error (#3740)
Browse files Browse the repository at this point in the history
  • Loading branch information
oldme-git authored Sep 13, 2024
1 parent 0e471ea commit e466938
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
21 changes: 21 additions & 0 deletions encoding/gxml/gxml.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,27 @@ func DecodeWithoutRoot(content []byte) (map[string]interface{}, error) {
return m, nil
}

// XMLEscapeChars 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:
" "
' '
< &lt;
> &gt;
& &amp;
*/
//
// Note: if XMLEscapeCharsDecoder(true) has been called - or the default, 'false,' value
// has been toggled to 'true' - then XMLEscapeChars(true) is ignored. If XMLEscapeChars(true)
// has already been called before XMLEscapeCharsDecoder(true), XMLEscapeChars(false) is called
// to turn escape encoding on mv.Xml, etc., to prevent double escaping ampersands, '&'.
func XMLEscapeChars(b ...bool) {
mxj.XMLEscapeChars(b...)
}

// Encode encodes map `m` to an XML format content as bytes.
// The optional parameter `rootTag` is used to specify the XML root tag.
func Encode(m map[string]interface{}, rootTag ...string) ([]byte, error) {
Expand Down
25 changes: 25 additions & 0 deletions encoding/gxml/gxml_z_unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,28 @@ func TestErrCase(t *testing.T) {
}
})
}

func Test_Issue3716(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
xml = `<Person><Bio>I am a software developer &amp; I love coding.</Bio><Email>[email protected]</Email><Name>&lt;&gt;&amp;&apos;&quot;AAA</Name></Person>`
m = map[string]interface{}{
"Person": map[string]interface{}{
"Name": "<>&'\"AAA",
"Email": "[email protected]",
"Bio": "I am a software developer & I love coding.",
},
}
)
gxml.XMLEscapeChars(true)
defer gxml.XMLEscapeChars(false)

xb, err := gxml.Encode(m)
t.AssertNil(err)
t.Assert(string(xb), xml)

dm, err := gxml.Decode(xb)
t.AssertNil(err)
t.Assert(dm, m)
})
}

0 comments on commit e466938

Please sign in to comment.