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

XPath in iterated sub-nodes #29

Closed benoitmasson closed 7 years ago

benoitmasson commented 7 years ago

Hello,

I'm facing an issue there, I don't know if this is standard XPath behavior or a bug in the lib...

Consider this XML string:

const xmlList = `
<list>
    <element>
        <title>foo</title>
    </element>
    <element>
        <title>bar</title>
    </element>
</list>
`

and this basic function:

func main() {
    elementPath := xmlpath.MustCompile(`//element`)
    titlePath := xmlpath.MustCompile(`//title`) // => same as /list/element/title
    root, err := xmlpath.Parse(strings.NewReader(xmlList))
    if err != nil {
        panic(err)
    }

    elementsIter := elementPath.Iter(root)
    for elementsIter.Next() {
        element := elementsIter.Node()
        fmt.Println("[DEBUG]", element.String())
        if title, ok := titlePath.String(element); ok {
            fmt.Println("[title]", title)
        }
        fmt.Println("--")
    }
}

It is meant to iterate through the <element> of the XML, and for each of them, extract with a sub-XPath their title.

The output is (I removed newlines and tabs, for clarity sake):

[DEBUG] foo
[title] foo
--
[DEBUG] bar
[title] foo
--

i.e., elements are iterated correctly, but titles are extracted from the root node (the same result is obtained if I use titlePath := xmlpath.MustCompile("/list/element/title"), while I clearly specified to parse from the element node...

Does anybody know what is going on here?

Thank you

benoitmasson commented 7 years ago

My bad, exactly the same issue as this one, in another context.

It is solved similarly, by replacing

xmlpath.MustCompile(`//title`) // starts from root node

by

xmlpath.MustCompile(`title`) // starts from the element

or

xmlpath.MustCompile(`./title`)