Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 5 additions & 1 deletion node.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,14 @@ func (n *Node) InnerText() string {
return b.String()
}

// xmlTextEscaper escapes the characters that are not allowed to appear
// literally in XML character data.
var xmlTextEscaper = strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;")

func outputXML(b *strings.Builder, n *Node, level int, skip bool) {
level++
if n.Type == TextNode {
b.WriteString(fmt.Sprintf("%v", n.value))
b.WriteString(xmlTextEscaper.Replace(fmt.Sprintf("%v", n.value)))
return
}
if v := reflect.ValueOf(n.value); v.Kind() == reflect.Slice {
Expand Down
25 changes: 25 additions & 0 deletions node_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package jsonquery

import (
"encoding/xml"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -161,3 +162,27 @@ func TestLargeFloat(t *testing.T) {
t.Fatalf("expected %v but %v", "365823929453", n.InnerText())
}
}

func TestOutputXMLEscapesText(t *testing.T) {
doc, err := parseString(`{"a": "x < y && y > z", "b": ["<i>", "AT&T"]}`)
if err != nil {
t.Fatal(err)
}
out := doc.OutputXML()
want := `<?xml version="1.0" encoding="utf-8"?><root><a>x &lt; y &amp;&amp; y &gt; z</a><b>&lt;i&gt;</b><b>AT&amp;T</b></root>`
if out != want {
t.Fatalf("OutputXML() = %s, want %s", out, want)
}

// The output must be well-formed and decode back to the original text.
var v struct {
A string `xml:"a"`
B []string `xml:"b"`
}
if err := xml.Unmarshal([]byte(out), &v); err != nil {
t.Fatalf("OutputXML() is not well-formed XML: %v", err)
}
if v.A != "x < y && y > z" || len(v.B) != 2 || v.B[0] != "<i>" || v.B[1] != "AT&T" {
t.Fatalf("decoded %+v", v)
}
}