How can I decode a specific child nested in an xml file?

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!

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

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])
    }
}
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)
	    }
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.