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
19 changes: 16 additions & 3 deletions node.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bufio"
"encoding/xml"
"fmt"
"html"
"io"
"strings"
)
Expand Down Expand Up @@ -245,11 +244,25 @@ func (i *indentation) writeIndent() (err error) {
return
}

// textEscaper escapes text like html.EscapeString, and also escapes carriage
// returns, which an XML parser would otherwise read back as newlines.
var textEscaper = strings.NewReplacer(
`&`, "&amp;", `'`, "&#39;", `<`, "&lt;", `>`, "&gt;", `"`, "&#34;",
"\r", "&#13;",
)

// attrEscaper escapes attribute values like textEscaper, and also escapes
// tabs and newlines, which an XML parser would otherwise read back as spaces.
var attrEscaper = strings.NewReplacer(
`&`, "&amp;", `'`, "&#39;", `<`, "&lt;", `>`, "&gt;", `"`, "&#34;",
"\t", "&#9;", "\n", "&#10;", "\r", "&#13;",
)

func outputXML(w io.Writer, n *Node, preserveSpaces bool, config *outputConfiguration, indent *indentation) (err error) {
preserveSpaces = calculatePreserveSpaces(n, preserveSpaces)
switch n.Type {
case TextNode:
_, err = io.WriteString(w, html.EscapeString(n.sanitizedData(preserveSpaces)))
_, err = io.WriteString(w, textEscaper.Replace(n.sanitizedData(preserveSpaces)))
return
case CharDataNode:
_, err = fmt.Fprintf(w, "<![CDATA[%v]]>", n.Data)
Expand Down Expand Up @@ -301,7 +314,7 @@ func outputXML(w io.Writer, n *Node, preserveSpaces bool, config *outputConfigur
return
}

_, err = fmt.Fprintf(w, `"%v"`, html.EscapeString(attr.Value))
_, err = fmt.Fprintf(w, `"%v"`, attrEscaper.Replace(attr.Value))
if err != nil {
return
}
Expand Down
24 changes: 24 additions & 0 deletions node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -848,3 +848,27 @@ func TestProcessingInstruction(t *testing.T) {
t.Errorf("Output mismatch:\nExpected: %s\nGot: %s", expected, output)
}
}

func TestOutputXMLKeepsWhitespaceCharacters(t *testing.T) {
s := `<a x="tab&#9;nl&#10;cr&#13;end" xml:space="preserve">one&#13;two</a>`
doc, err := Parse(strings.NewReader(s))
if err != nil {
t.Fatal(err)
}
a := FindOne(doc, "//a")
if got, want := a.SelectAttr("x"), "tab\tnl\ncr\rend"; got != want {
t.Fatalf("attribute: got %q, want %q", got, want)
}

reparsed, err := Parse(strings.NewReader(doc.OutputXML(true)))
if err != nil {
t.Fatal(err)
}
b := FindOne(reparsed, "//a")
if got, want := b.SelectAttr("x"), a.SelectAttr("x"); got != want {
t.Errorf("attribute after round trip: got %q, want %q", got, want)
}
if got, want := b.InnerText(), a.InnerText(); got != want {
t.Errorf("text after round trip: got %q, want %q", got, want)
}
}