https://github.com/speedata/cxpath
A programmer's friendly interface to XPath
https://github.com/speedata/cxpath
golang xpath xpath2
Last synced: about 1 month ago
JSON representation
A programmer's friendly interface to XPath
- Host: GitHub
- URL: https://github.com/speedata/cxpath
- Owner: speedata
- License: bsd-3-clause
- Created: 2024-11-28T08:32:16.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2026-05-03T10:23:19.000Z (about 2 months ago)
- Last Synced: 2026-05-03T12:22:39.963Z (about 2 months ago)
- Topics: golang, xpath, xpath2
- Language: Go
- Homepage:
- Size: 11.7 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: Readme.md
- License: License.md
Awesome Lists containing this project
README
[](https://pkg.go.dev/github.com/speedata/cxpath)
# cxpath - a programmer's friendly interface to XPath
With cxpath you can access XML files via XPath 2.0 in a Go friendly matter.
```xml
text
```
```go
package main
import (
"fmt"
"log"
"github.com/speedata/cxpath"
)
func dothings() error {
ctx, err := cxpath.NewFromFile("myfile.xml")
if err != nil {
return err
}
// for XPath queries
ctx.SetNamespace("a", "anamespace")
root := ctx.Root()
// prints 'root'
fmt.Println(root.Eval("local-name()"))
// prints sub
fmt.Println(root.Eval("local-name(a:sub)"))
// prints anamespace
fmt.Println(root.Eval("namespace-uri(a:sub)"))
sub := root.Eval("a:sub")
for cp := range sub.Each("string-to-codepoints(.)") {
// prints 116, 101, 120, 116 - the codepoints for 'text'
fmt.Println(cp)
}
return nil
}
func main() {
if err := dothings(); err != nil {
log.Fatal(err)
}
}
```
## Error handling
The constructors `NewFromFile` and `NewFromReader` return errors the usual Go way.
For all other methods, errors are stored in the `Error` field of the returned `Context` so that method chaining stays clean:
```go
root := ctx.Root()
result := root.Eval("some/xpath")
if result.Error != nil {
log.Fatal(result.Error)
}
fmt.Println(result.String())
```
The same applies to the `Each` iterator. If the XPath expression is invalid, the iterator yields a single `Context` with the `Error` field set:
```go
for item := range root.Each("some/xpath") {
if item.Error != nil {
log.Fatal(item.Error)
}
fmt.Println(item.Int())
}
```
The value accessors `Int()` and `Bool()` also store conversion errors in `Context.Error` rather than returning them directly.
## Installation
go get github.com/speedata/cxpath