Skip to content

Commit

Permalink
Merge PR #9 from zhao5908/output-xml
Browse files Browse the repository at this point in the history
  • Loading branch information
zhengchun committed Dec 23, 2018
2 parents 431a9e9 + e31a81f commit ac5cca7
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
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")
}
}

0 comments on commit ac5cca7

Please sign in to comment.