1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
|
package xmlpath
import (
"golang.org/x/net/html"
"encoding/xml"
"io"
"strings"
)
// Node is an item in an xml tree that was compiled to
// be processed via xml paths. A node may represent:
//
// - An element in the xml document (<body>)
// - An attribute of an element in the xml document (href="...")
// - A comment in the xml document (<!--...-->)
// - A processing instruction in the xml document (<?...?>)
// - Some text within the xml document
//
type Node struct {
kind nodeKind
name xml.Name
attr string
text []byte
nodes []Node
pos int
end int
up *Node
down []*Node
}
type nodeKind int
const (
anyNode nodeKind = iota
startNode
endNode
attrNode
textNode
commentNode
procInstNode
)
// String returns the string value of node.
//
// The string value of a node is:
//
// - For element nodes, the concatenation of all text nodes within the element.
// - For text nodes, the text itself.
// - For attribute nodes, the attribute value.
// - For comment nodes, the text within the comment delimiters.
// - For processing instruction nodes, the content of the instruction.
//
func (node *Node) String() string {
if node.kind == attrNode {
return node.attr
}
return string(node.Bytes())
}
// Bytes returns the string value of node as a byte slice.
// See Node.String for a description of what the string value of a node is.
func (node *Node) Bytes() []byte {
if node.kind == attrNode {
return []byte(node.attr)
}
if node.kind != startNode {
return node.text
}
size := 0
for i := node.pos; i < node.end; i++ {
if node.nodes[i].kind == textNode {
size += len(node.nodes[i].text)
}
}
text := make([]byte, 0, size)
for i := node.pos; i < node.end; i++ {
if node.nodes[i].kind == textNode {
text = append(text, node.nodes[i].text...)
}
}
return text
}
// equals returns whether the string value of node is equal to s,
// without allocating memory.
func (node *Node) equals(s string) bool {
if node.kind == attrNode {
return s == node.attr
}
if node.kind != startNode {
if len(s) != len(node.text) {
return false
}
for i := range s {
if s[i] != node.text[i] {
return false
}
}
return true
}
si := 0
for i := node.pos; i < node.end; i++ {
if node.nodes[i].kind == textNode {
for _, c := range node.nodes[i].text {
if si > len(s) {
return false
}
if s[si] != c {
return false
}
si++
}
}
}
return si == len(s)
}
// contains returns whether the string value of node contains s,
// without allocating memory.
func (node *Node) contains(s string) (ok bool) {
if len(s) == 0 {
return true
}
if node.kind == attrNode {
return strings.Contains(node.attr, s)
}
s0 := s[0]
for i := node.pos; i < node.end; i++ {
if node.nodes[i].kind == textNode {
text := node.nodes[i].text
NextTry:
for ci, c := range text {
if c != s0 {
continue
}
si := 1
for ci++; ci < len(text) && si < len(s); ci++ {
if s[si] != text[ci] {
continue NextTry
}
si++
}
if si == len(s) {
return true
}
for j := i + 1; j < node.end; j++ {
if node.nodes[j].kind == textNode {
for _, c := range node.nodes[j].text {
if s[si] != c {
continue NextTry
}
si++
if si == len(s) {
return true
}
}
}
}
}
}
}
return false
}
// Parse reads an xml document from r, parses it, and returns its root node.
func Parse(r io.Reader) (*Node, error) {
return ParseDecoder(xml.NewDecoder(r))
}
// ParseDecoder parses the xml document being decoded by d and returns
// its root node.
func ParseDecoder(d *xml.Decoder) (*Node, error) {
var nodes []Node
var text []byte
// The root node.
nodes = append(nodes, Node{kind: startNode})
for {
t, err := d.Token()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
switch t := t.(type) {
case xml.EndElement:
nodes = append(nodes, Node{
kind: endNode,
})
case xml.StartElement:
nodes = append(nodes, Node{
kind: startNode,
name: t.Name,
})
for _, attr := range t.Attr {
nodes = append(nodes, Node{
kind: attrNode,
name: attr.Name,
attr: attr.Value,
})
}
case xml.CharData:
texti := len(text)
text = append(text, t...)
nodes = append(nodes, Node{
kind: textNode,
text: text[texti : texti+len(t)],
})
case xml.Comment:
texti := len(text)
text = append(text, t...)
nodes = append(nodes, Node{
kind: commentNode,
text: text[texti : texti+len(t)],
})
case xml.ProcInst:
texti := len(text)
text = append(text, t.Inst...)
nodes = append(nodes, Node{
kind: procInstNode,
name: xml.Name{Local: t.Target},
text: text[texti : texti+len(t.Inst)],
})
}
}
// Close the root node.
nodes = append(nodes, Node{kind: endNode})
stack := make([]*Node, 0, len(nodes))
downs := make([]*Node, len(nodes))
downCount := 0
for pos := range nodes {
switch nodes[pos].kind {
case startNode, attrNode, textNode, commentNode, procInstNode:
node := &nodes[pos]
node.nodes = nodes
node.pos = pos
if len(stack) > 0 {
node.up = stack[len(stack)-1]
}
if node.kind == startNode {
stack = append(stack, node)
} else {
node.end = pos + 1
}
case endNode:
node := stack[len(stack)-1]
node.end = pos
stack = stack[:len(stack)-1]
// Compute downs. Doing that here is what enables the
// use of a slice of a contiguous pre-allocated block.
node.down = downs[downCount:downCount]
for i := node.pos + 1; i < node.end; i++ {
if nodes[i].up == node {
switch nodes[i].kind {
case startNode, textNode, commentNode, procInstNode:
node.down = append(node.down, &nodes[i])
downCount++
}
}
}
if len(stack) == 0 {
return node, nil
}
}
}
return nil, io.EOF
}
// ParseHTML reads an HTML document from r, parses it using a proper HTML
// parser, and returns its root node.
//
// The document will be processed as a properly structured HTML document,
// emulating the behavior of a browser when processing it. This includes
// putting the content inside proper <html> and <body> tags, if the
// provided text misses them.
func ParseHTML(r io.Reader) (*Node, error) {
ns, err := html.ParseFragment(r, nil)
if err != nil {
return nil, err
}
var nodes []Node
var text []byte
n := ns[0]
// The root node.
nodes = append(nodes, Node{kind: startNode})
for n != nil {
switch n.Type {
case html.DocumentNode:
case html.ElementNode:
nodes = append(nodes, Node{
kind: startNode,
name: xml.Name{Local: n.Data, Space: n.Namespace},
})
for _, attr := range n.Attr {
nodes = append(nodes, Node{
kind: attrNode,
name: xml.Name{Local: attr.Key, Space: attr.Namespace},
attr: attr.Val,
})
}
case html.TextNode:
texti := len(text)
text = append(text, n.Data...)
nodes = append(nodes, Node{
kind: textNode,
text: text[texti : texti+len(n.Data)],
})
case html.CommentNode:
texti := len(text)
text = append(text, n.Data...)
nodes = append(nodes, Node{
kind: commentNode,
text: text[texti : texti+len(n.Data)],
})
}
if n.FirstChild != nil {
n = n.FirstChild
continue
}
for n != nil {
if n.Type == html.ElementNode {
nodes = append(nodes, Node{kind: endNode})
}
if n.NextSibling != nil {
n = n.NextSibling
break
}
n = n.Parent
}
}
// Close the root node.
nodes = append(nodes, Node{kind: endNode})
stack := make([]*Node, 0, len(nodes))
downs := make([]*Node, len(nodes))
downCount := 0
for pos := range nodes {
switch nodes[pos].kind {
case startNode, attrNode, textNode, commentNode, procInstNode:
node := &nodes[pos]
node.nodes = nodes
node.pos = pos
if len(stack) > 0 {
node.up = stack[len(stack)-1]
}
if node.kind == startNode {
stack = append(stack, node)
} else {
node.end = pos + 1
}
case endNode:
node := stack[len(stack)-1]
node.end = pos
stack = stack[:len(stack)-1]
// Compute downs. Doing that here is what enables the
// use of a slice of a contiguous pre-allocated block.
node.down = downs[downCount:downCount]
for i := node.pos + 1; i < node.end; i++ {
if nodes[i].up == node {
switch nodes[i].kind {
case startNode, textNode, commentNode, procInstNode:
node.down = append(node.down, &nodes[i])
downCount++
}
}
}
if len(stack) == 0 {
return node, nil
}
}
}
return nil, io.EOF
}
|