github.com/fluhus/gostuff@v0.4.1-0.20240331134726-be71864f2b5d/xmlnode/read_test.go (about)

     1  package xmlnode
     2  
     3  import (
     4  	"strings"
     5  	"testing"
     6  )
     7  
     8  func TestReadAll(t *testing.T) {
     9  	text := "<hello>world<?proc inst?><goodbye until=\"later\"><!mydirective>world<!--My comment--></goodbye></hello>"
    10  	node, err := ReadAll(strings.NewReader(text))
    11  
    12  	if err != nil {
    13  		t.Fatal(err)
    14  	}
    15  
    16  	result := nodeToString(node)
    17  	if result != text {
    18  		t.Fatal("expected:", text, "actual:", result)
    19  	}
    20  }
    21  
    22  // Inefficient stringifier for testing.
    23  func nodeToString(n Node) string {
    24  	switch n := n.(type) {
    25  	case *root:
    26  		result := ""
    27  		for _, child := range n.children {
    28  			result += nodeToString(child)
    29  		}
    30  		return result
    31  
    32  	case *tag:
    33  		result := "<" + n.tagName
    34  		for _, attr := range n.attr {
    35  			result += " " + attr.Name.Local + "=\"" + attr.Value + "\""
    36  		}
    37  		result += ">"
    38  		for _, child := range n.children {
    39  			result += nodeToString(child)
    40  		}
    41  		result += "</" + n.tagName + ">"
    42  		return result
    43  
    44  	case *text:
    45  		return n.text
    46  
    47  	case *comment:
    48  		return "<!--" + n.comment + "-->"
    49  
    50  	case *procInst:
    51  		return "<?" + n.target + " " + n.inst + "?>"
    52  
    53  	case *directive:
    54  		return "<!" + n.directive + ">"
    55  
    56  	default:
    57  		panic("Unknown node type.")
    58  	}
    59  }