M-A
(M-A)
September 15, 2020, 2:45pm
1
so lets say for example I have this xml:
<container>
<children>
<child type="M">1</child>
<child type="C">2</child>
<child type="W">3</child>
</children>
</container>
how can I say I want the child that contains type C, If i have a struct like this:
type Container struct {
Container Child `xml:"container>children"`
}
type Child struct {
Type string `cml:"type,attr"`
Child int `xml:"child"`
}
me having this ^ will return the first child. But I want the 2nd or 3rd child. Is there a way to write this without iterating through the xml?
Thank you!
skillian
(Sean Killian)
September 16, 2020, 11:16am
2
I don’t think this can be done with Go’s builtin XML library. Here’s an XPath implementation that might so what you want: https://github.com/antchfx/xmlquery
clbanning
(Charles Banning)
September 17, 2020, 11:31am
3
package main
import (
"fmt"
"github.com/clbanning/mxj"
)
func main() {
data := []byte(`<container>
<children>
<child type="M">1</child>
<child type="C">2</child>
<child type="W">3</child>
</children>
</container>`)
m, err := mxj.NewMapXml(data)
if err != nil {
fmt.Println("NewMapXml err:", err)
return
}
vals, err := m.ValuesForKey("-type")
if err != nil {
fmt.Println("ValuesForKey err:", err)
return
}
for i := 1; i < 3; i++ {
fmt.Println(i, "is:", vals[i])
}
}
clbanning
(Charles Banning)
September 17, 2020, 5:29pm
4
package main
import (
"fmt"
"strconv"
"github.com/clbanning/mxj"
)
func main() {
data := []byte(`<container>
<children>
<child type="M">1</child>
<child type="C">2</child>
<child type="W">3</child>
</children>
</container>`)
mxj.PrependAttrWithHyphen(false)
m, err := mxj.NewMapXml(data)
if err != nil {
fmt.Println("NewMapXml err:", err)
return
}
for i := 1; i < 3; i++ {
val, err := m.ValueForPath("container.children.child["+strconv.Itoa(i)+"].type")
if err != nil {
fmt.Println("ValuesForKey err:", err)
return
}
fmt.Println(i, "is:", val)
}
}
system
(system)
Closed
December 16, 2020, 5:29pm
5
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.