Added Node.SetValue(string) method.

SetValue replaces all children of the current node with a single NT_TEXT node and sets its Value to the given parameter.
This lets us replace node values before writing out the document.
This commit is contained in:
Guido Witmond 2015-01-05 17:13:46 +01:00
parent 745ca85455
commit 17e1b69620
2 changed files with 82 additions and 0 deletions

View File

@ -66,6 +66,13 @@ func (this *Node) GetValue() string {
return res return res
} }
func (this *Node) SetValue(val string) {
t := NewNode(NT_TEXT)
t.Value = string([]byte(val))
t.Parent = this
this.Children = []*Node{t} // brutally replace all other children
}
// Get node value as string // Get node value as string
func (this *Node) S(namespace, name string) string { func (this *Node) S(namespace, name string) string {
foundNode := rec_SelectNode(this, namespace, name) foundNode := rec_SelectNode(this, namespace, name)

View File

@ -251,3 +251,78 @@ func TestElementNodeValueFetch(t *testing.T) {
t.Errorf("Failed to get availability using B, got: %v, wanted: true", v) t.Errorf("Failed to get availability using B, got: %v, wanted: true", v)
} }
} }
func TestElementNodeValueFetchAndSet(t *testing.T) {
IndentPrefix = ""
data := `<car><color>
r<cool />
ed</color><brand>BM<awesome />W</brand><price>50
<cheap />.25</price><count>6
<small />2
</count><available>
Tr
<found />
ue</available></car>`
doc := New()
if err := doc.LoadString(data, nil); nil != err {
t.Fatalf("LoadString(): %s", err)
}
carN := doc.SelectNode("", "car")
if carN == nil {
t.Fatalf("Failed to get the car, got nil, wanted Node{car}")
}
colorNode := carN.SelectNode("", "color")
if colorNode == nil {
t.Fatalf("Failed to get the color, got nil, wanted Node{color}")
}
colorVal := colorNode.GetValue()
if colorVal != "red" {
t.Fatalf("Failed to get the color, got %v, wanted 'red'", colorVal)
}
colorNode.SetValue("blue")
expected := `<car><color>blue</color><brand>BM<awesome />W</brand><price>50
<cheap />.25</price><count>6
<small />2
</count><available>
Tr
<found />
ue</available></car>`
if got := doc.Root.String(); got != expected {
t.Fatalf("expected: \n%s\ngot: \n%s\n", expected, got)
}
// now set the brand
brandNode := carN.SelectNode("", "brand")
if brandNode == nil {
t.Fatalf("Failed to get the color, got nil, wanted Node{brand}")
}
brandVal := brandNode.GetValue()
if brandVal != "BMW" {
t.Fatalf("Failed to get the brand, got %v, wanted 'BMW'", brandVal)
}
brandNode.SetValue("Trabant")
// Notice, we lose the <awesome /> tag in BMW, that's intentional
expected = `<car><color>blue</color><brand>Trabant</brand><price>50
<cheap />.25</price><count>6
<small />2
</count><available>
Tr
<found />
ue</available></car>`
if got := doc.Root.String(); got != expected {
t.Fatalf("expected: \n%s\ngot: \n%s\n", expected, got)
}
}