Skip to content

Convenience Functions #16

@astockwell

Description

@astockwell

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions