Aru*_*unL 4 xml recursion xpath go
我试图在html文档上执行xpath操作.我想做一个两级xpath查询.html文档"index.html"如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="head">
<div class="area">
<div class="value">10</div>
</div>
<div class="area">
<div class="value">20</div>
</div>
<div class="area">
<div class="value">30</div>
</div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我想首先使用class ="area"获取所有div,然后使用Gokogiri在golang中使用class ="value"递归获取div.
我的代码如下:package main
import (
"fmt"
"io/ioutil"
"github.com/moovweb/gokogiri"
"github.com/moovweb/gokogiri/xpath"
)
func main() {
content, _ := ioutil.ReadFile("index.html")
doc, _ := gokogiri.ParseHtml(content)
defer doc.Free()
xps := xpath.Compile("//div[@class='head']/div[@class='area']")
xpw := xpath.Compile("//div[@class='value']")
ss, _ := doc.Root().Search(xps)
for _, s := range ss {
ww, _ := s.Search(xpw)
for _, w := range ww {
fmt.Println(w.InnerHtml())
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我得到的输出很奇怪:
10
20
30
10
20
30
10
20
30
Run Code Online (Sandbox Code Playgroud)
我打算得到:
10
20
30
Run Code Online (Sandbox Code Playgroud)
我想递归搜索xpath模式.我认为我的二级xpath模式有问题.看来,我的第二级xpath再次搜索整个文档,而不是使用class ="area"的单个div.如何进行递归xpath模式搜索?我很感激任何帮助.
来自任何节点的XPath搜索仍然可以搜索整个树.
如果您只想搜索子树,可以使用a .(假设您仍然需要后代或自己)来启动表达式,否则使用精确路径.
xps := xpath.Compile("//div[@class='head']/div[@class='area']")
xpw := xpath.Compile(".//div[@class='value']")
// this works in your example case
// xpw := xpath.Compile("div[@class='value']")
// as does this
// xpw := xpath.Compile("./div[@class='value']")
ss, _ := doc.Root().Search(xps)
for _, s := range ss {
ww, _ := s.Search(xpw)
for _, w := range ww {
fmt.Println(w.InnerHtml())
}
}
Run Code Online (Sandbox Code Playgroud)
打印:
10
20
30
Run Code Online (Sandbox Code Playgroud)