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

updated: output xml with comment node. #9

Merged
merged 2 commits into from
Dec 23, 2018
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
13 changes: 12 additions & 1 deletion node.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,16 @@ func (n *Node) InnerText() string {
}

func outputXML(buf *bytes.Buffer, n *Node) {
if n.Type == TextNode || n.Type == CommentNode {
if n.Type == TextNode {
xml.EscapeText(buf, []byte(strings.TrimSpace(n.Data)))
return
}
if n.Type == CommentNode {
buf.WriteString("<!--")
buf.WriteString(n.Data)
buf.WriteString("-->")
return
}
if n.Type == DeclarationNode {
buf.WriteString("<?" + n.Data)
} else {
Expand Down Expand Up @@ -258,6 +264,11 @@ func parse(r io.Reader) (*Node, error) {
addSibling(prev, node)
} else if level > prev.level {
addChild(prev, node)
} else if level < prev.level {
for i := prev.level - level; i > 1; i-- {
prev = prev.Parent
}
addSibling(prev.Parent, node)
}
case xml.ProcInst: // Processing Instruction
if prev.Type != DeclarationNode {
Expand Down
27 changes: 27 additions & 0 deletions node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,3 +317,30 @@ func TestAttributeWithNamespace(t *testing.T) {
t.Fatal("n is nil")
}
}

func TestOutputXMLWithCommentNode(t *testing.T) {
s := `<?xml version="1.0" encoding="utf-8"?>
<!-- Students grades are updated bi-monthly -->
<class_list>
<student>
<name>Robert</name>
<grade>A+</grade>
</student>
<!--
<student>
<name>Lenard</name>
<grade>A-</grade>
</student>
-->
</class_list>`
doc, _ := Parse(strings.NewReader(s))
t.Log(doc.OutputXML(true))
if e, g := "<!-- Students grades are updated bi-monthly -->", doc.OutputXML(true); strings.Index(g, e) == -1 {
t.Fatal("missing some comment-node.")
}
n := FindOne(doc, "//class_list")
t.Log(n.OutputXML(false))
if e, g := "<name>Lenard</name>", n.OutputXML(false); strings.Index(g, e) == -1 {
t.Fatal("missing some comment-node")
}
}