MCPcopy Create free account
hub / github.com/antchfx/xmlquery / Example

Function Example

doc_test.go:11–64  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

9)
10
11func Example() {
12 // XPATH syntax and functions see https://github.com/antchfx/xpath
13 s := `<?xml version="1.0"?>
14 <bookstore>
15 <book id="bk101">
16 <author>Gambardella, Matthew</author>
17 <title>XML Developer's Guide</title>
18 <genre>Computer</genre>
19 <price>44.95</price>
20 <publish_date>2000-10-01</publish_date>
21 </book>
22 <book id="bk102">
23 <author>Ralls, Kim</author>
24 <title>Midnight Rain</title>
25 <genre>Fantasy</genre>
26 <price>5.95</price>
27 <publish_date>2000-12-16</publish_date>
28 </book>
29 <book id="bk103">
30 <author>Corets, Eva</author>
31 <title>Maeve Ascendant</title>
32 <genre>Fantasy</genre>
33 <price>5.95</price>
34 <publish_date>2000-11-17</publish_date>
35 </book>
36 </bookstore>`
37
38 doc, err := xmlquery.Parse(strings.NewReader(s))
39 if err != nil {
40 panic(err)
41 }
42 // Quick query all books.
43 books := xmlquery.Find(doc, `/bookstore/book`)
44 for _, n := range books {
45 fmt.Println(n)
46 }
47
48 // Find all books with price rather than 10.
49 books = xmlquery.Find(doc, `//book[price < 10]`)
50 fmt.Println(len(books))
51
52 // Find books with @id=bk102 or @id=bk101
53 books = xmlquery.Find(doc, `//book[@id = "bk102" or @id = "bk101"]`)
54 fmt.Println(len(books))
55
56 // Find books by author: Corets, Eva
57 book := xmlquery.FindOne(doc, `//book[author = "Corets, Eva"]`)
58 fmt.Println(book.SelectElement("title").InnerText()) // > Output: Maeve Ascendant
59
60 // Calculate the total prices of all books
61 nav := xmlquery.CreateXPathNavigator(doc)
62 prices := xpath.MustCompile(`sum(//book/price)`).Evaluate(nav).(float64)
63 fmt.Println(prices) // > Output: 56.85
64}

Callers

nothing calls this directly

Calls 6

ParseFunction · 0.92
FindFunction · 0.92
FindOneFunction · 0.92
CreateXPathNavigatorFunction · 0.92
InnerTextMethod · 0.80
SelectElementMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…