go-xmlpath / xmlpath

Strict subset of the XPath specification for the Go language.
http://gopkg.in/xmlpath.v2
Other
115 stars 37 forks source link

Convenience Functions #16

Open astockwell opened 9 years ago

astockwell commented 9 years ago

Do you feel there'd be any value in adding the following 2 convenience functions? I find myself re-writing them over and over with literally no variation (and others seem to as well, e.g. Issue #11 ), and so I got to thinking they would be really useful to just pull in to the package itself.

This is not tested code, just meant for discussion (function names are inspired by the standard regexp library - I'm not married to them):

// Finds all matching node's string values
func FindAllString(xml, xpath string) ([]string, error) { 

    path, err := xmlpath.Compile(xpath)
    if err != nil {
        return nil, err
    }

    root, err := xmlpath.Parse(strings.NewReader(xml))
    if err != nil {
        return nil, err
    }

    ss := []string{}

    i := path.Iter(root)
    for iter.Next() {
        s := iter.Node().String()
        ss = append(ss, strings.TrimSpace(s))
    }

    return ss, nil  
}

// Finds first matching node's string value
// Use when there's only one expected matching node
func FindString(xml, xpath string) (string, error) { 
    ss, err := FindAllString(xml, xpath string)
    if err != nil {
        return "", err
    }

    return ss[0], nil
}