Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(encoding/gxml): XML special character encoding error #3740

Merged
merged 7 commits into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
24 changes: 24 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,27 @@ 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)
gqcn marked this conversation as resolved.
Show resolved Hide resolved

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)
})
}
Loading