Skip to content

Commit

Permalink
add WithPreserveSpace option when OutputXMLWithOptions
Browse files Browse the repository at this point in the history
  • Loading branch information
elsejj committed Jun 21, 2023
1 parent c9d411c commit 56cac1c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
12 changes: 11 additions & 1 deletion node.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ func WithoutComments() OutputOption {
}
}

// WithPreserveSpace will preserve spaces in output
func WithPreserveSpace() OutputOption {
return func(oc *outputConfiguration) {
oc.preserveSpaces = true
}
}

func newXMLName(name string) xml.Name {
if i := strings.IndexByte(name, ':'); i > 0 {
return xml.Name{
Expand Down Expand Up @@ -216,8 +223,11 @@ func (n *Node) OutputXMLWithOptions(opts ...OutputOption) string {
for _, opt := range opts {
opt(config)
}
pastPreserveSpaces := config.preserveSpaces
// restore the default value, for compatibility
config.preserveSpaces = false

preserveSpaces := calculatePreserveSpaces(n, false)
preserveSpaces := calculatePreserveSpaces(n, pastPreserveSpaces)
var b strings.Builder
if config.printSelf && n.Type != DocumentNode {
outputXML(&b, n, preserveSpaces, config)
Expand Down
19 changes: 19 additions & 0 deletions node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -592,3 +592,22 @@ func TestOutputXMLWithOptions(t *testing.T) {
t.Errorf("output was not expected. expected %v but got %v", expected, result)
}
}

func TestOutputXMLWithPreserveSpaceOption(t *testing.T) {
s := `<?xml version="1.0" encoding="utf-8"?>
<class_list>
<student>
<name> Robert </name>
<grade>A+</grade>
</student>
</class_list>`
doc, _ := Parse(strings.NewReader(s))
resultWithSpace := doc.OutputXMLWithOptions(WithPreserveSpace())
resultWithoutSpace := doc.OutputXMLWithOptions()
if !strings.Contains(resultWithSpace, "> Robert <") {
t.Errorf("output was not expected. expected %v but got %v", " Robert ", resultWithSpace)
}
if !strings.Contains(resultWithoutSpace, ">Robert<") {
t.Errorf("output was not expected. expected %v but got %v", " Robert ", resultWithoutSpace)
}
}

0 comments on commit 56cac1c

Please sign in to comment.