Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convenience Functions #16

Open
astockwell opened this issue Oct 16, 2015 · 0 comments
Open

Convenience Functions #16

astockwell opened this issue Oct 16, 2015 · 0 comments

Comments

@astockwell
Copy link

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant