antchfx / xmlquery

xmlquery is Golang XPath package for XML query.
https://github.com/antchfx/xpath
MIT License
444 stars 89 forks source link

substring-before always returns <nil> node #29

Closed srebhan closed 4 years ago

srebhan commented 4 years ago

When executing the following code

package main

import (
    "fmt"
    "strings"

    "github.com/antchfx/xmlquery"
)

func main(){
    xml := `
    <?xml version="1.0"?>
    <Test>
      <Variable Name="test-a-b/c"/>
    </Test>
    `
    query := "/Test/Variable/@Name"
    // query := "substring-before(/Test/Variable/@Name, '-')"

    // Parse the XML
    doc, err := xmlquery.Parse(strings.NewReader(xml))
    if err != nil {
        panic(err)
    }

    // Queries
    node, err := xmlquery.Query(doc, query)
    if err != nil {
        panic(err)
    }
    if node == nil {
        fmt.Print("Node is nil\n")
    } else {
        fmt.Printf("Result: %v\n", node.InnerText())
    }
}

with the first query, the node is found correctly and I do get the text of the attribute 'test-a-b/c' as expected.

However, when using the second query with substring-before I do get a nil node and the print-out is 'Node is nil', when the expected result is the string 'test'.

Is there an error in the code above or is this an issue in xmlquery?

zhengchun commented 4 years ago

Use xpath.Eval() instead of xmlquery.Query(). The xmlquery.Query() function only executing a query(including logical operation) not do computing.

// Parse the XML
    doc, err := xmlquery.Parse(strings.NewReader(xml))
    if err != nil {
        panic(err)
    }
    query = "substring-before(/Test/Variable/@Name, '-')"
    exp := xpath.MustCompile(query)
    v := exp.Evaluate(xmlquery.CreateXPathNavigator(doc))
    fmt.Println(v.(string))