Perform path queries with XPath-like syntax
mainetree supports lightweight XPath-like queries to find elements within a document.
Query Types
- Recursive Search: Use the
//prefix to search for elements at any level of the hierarchy (e.g.,//book[@category='WEB']/title). - Direct Path: Use
./or absolute paths to navigate specific hierarchies (e.g.,./bookstore/book[1]/*). - Predicates: Use square brackets
[]for filtering, such as attribute matching[@attr='val']or index selection[1].
Methods
FindElementsSeq(path): Executes a path query and returns a sequence of matching elements.FindElementsPathSeq(compiledPath): Executes a query using a pre-compiled path object. Use this for performance if you plan to run the same query multiple times.MustCompilePath(path): Compiles a path string into a path object. It panics if the path is invalid.
// Recursive search
for _, t := range doc.FindElementsSeq("//book[@category='WEB']/title") {
fmt.Println("Title:", t.Text())
}
// Direct path with index and wildcard
for _, e := range doc.FindElementsSeq("./bookstore/book[1]/*") {
fmt.Printf("%s: %s\n", e.Tag, e.Text())
}
// Using pre-compiled paths for performance
path := etree.MustCompilePath("./bookstore/book[p:price='49.99']/title")
for _, e := doc.FindElementsPathSeq(path) {
fmt.Println(e.Text())
}