diff --git a/src/node.go b/src/node.go index 8a8b33c..0663158 100644 --- a/src/node.go +++ b/src/node.go @@ -1,5 +1,7 @@ package xmlx +import "os" +import "strings" import "xml" import "fmt" import "strconv" @@ -24,13 +26,17 @@ type Node struct { Attributes []Attr; Parent *Node; Value string; - - // procinst field - Target string; + Target string; // procinst field } func NewNode(tid byte) *Node { return &Node{Type: tid} } +// This wraps the standard xml.Unmarshal function and supplies this particular +// node as the content to be unmarshalled. +func (this *Node) Unmarshal(obj interface{}) os.Error { + return xml.Unmarshal(strings.NewReader(this.String()), obj); +} + // Get node value as string func (this *Node) GetValue(namespace, name string) string { node := rec_SelectNode(this, namespace, name); diff --git a/src/xmlx_test.go b/src/xmlx_test.go index dd07a09..999e35a 100644 --- a/src/xmlx_test.go +++ b/src/xmlx_test.go @@ -70,3 +70,41 @@ func TestNodeSearch(t *testing.T) { } } +type Image struct { + Title string; + Url string; + Link string; + Width string; + Height string; + Description string; +} + +func TestUnmarshal(t *testing.T) { + doc := New(); + err := doc.LoadFile("test.xml"); + + if err != nil { + t.Errorf("LoadFile(): %s", err); + return; + } + + node := doc.SelectNode("", "image"); + if node == nil { + t.Errorf("SelectNode(): No node found."); + return; + } + + img := Image{}; + err = node.Unmarshal(&img); + if err != nil { + t.Errorf("Unmarshal(): %s", err); + return; + } + + if img.Title != "WriteTheWeb" { + t.Errorf("Image.Title has incorrect value. Got '%s', expected 'WriteTheWeb'.", img.Title); + return; + } +} + +