Added *node.Unmarshal() method

This commit is contained in:
jim teeuwen 2009-12-02 19:38:35 +01:00
parent ccb91f470e
commit 664e4ae0d2
2 changed files with 47 additions and 3 deletions

View File

@ -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);

View File

@ -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;
}
}