| 1 |
# XML [](https://pkg.go.dev/github.com/tdewolff/parse/v2/xml?tab=doc) |
| 2 |
|
| 3 |
This package is an XML lexer written in [Go][1]. It follows the specification at [Extensible Markup Language (XML) 1.0 (Fifth Edition)](http://www.w3.org/TR/REC-xml/). The lexer takes an io.Reader and converts it into tokens until the EOF. |
| 4 |
|
| 5 |
## Installation |
| 6 |
Run the following command |
| 7 |
|
| 8 |
go get -u github.com/tdewolff/parse/v2/xml |
| 9 |
|
| 10 |
or add the following import and run project with `go get` |
| 11 |
|
| 12 |
import "github.com/tdewolff/parse/v2/xml" |
| 13 |
|
| 14 |
## Lexer |
| 15 |
### Usage |
| 16 |
The following initializes a new Lexer with io.Reader `r`: |
| 17 |
``` go |
| 18 |
l := xml.NewLexer(parse.NewInput(r)) |
| 19 |
``` |
| 20 |
|
| 21 |
To tokenize until EOF an error, use: |
| 22 |
``` go |
| 23 |
for { |
| 24 |
tt, data := l.Next() |
| 25 |
switch tt { |
| 26 |
case xml.ErrorToken: |
| 27 |
// error or EOF set in l.Err() |
| 28 |
return |
| 29 |
case xml.StartTagToken: |
| 30 |
// ... |
| 31 |
for { |
| 32 |
ttAttr, dataAttr := l.Next() |
| 33 |
if ttAttr != xml.AttributeToken { |
| 34 |
// handle StartTagCloseToken/StartTagCloseVoidToken/StartTagClosePIToken |
| 35 |
break |
| 36 |
} |
| 37 |
// ... |
| 38 |
} |
| 39 |
case xml.EndTagToken: |
| 40 |
// ... |
| 41 |
} |
| 42 |
} |
| 43 |
``` |
| 44 |
|
| 45 |
All tokens: |
| 46 |
``` go |
| 47 |
ErrorToken TokenType = iota // extra token when errors occur |
| 48 |
CommentToken |
| 49 |
CDATAToken |
| 50 |
StartTagToken |
| 51 |
StartTagCloseToken |
| 52 |
StartTagCloseVoidToken |
| 53 |
StartTagClosePIToken |
| 54 |
EndTagToken |
| 55 |
AttributeToken |
| 56 |
TextToken |
| 57 |
``` |
| 58 |
|
| 59 |
### Examples |
| 60 |
``` go |
| 61 |
package main |
| 62 |
|
| 63 |
import ( |
| 64 |
"os" |
| 65 |
|
| 66 |
"github.com/tdewolff/parse/v2/xml" |
| 67 |
) |
| 68 |
|
| 69 |
// Tokenize XML from stdin. |
| 70 |
func main() { |
| 71 |
l := xml.NewLexer(parse.NewInput(os.Stdin)) |
| 72 |
for { |
| 73 |
tt, data := l.Next() |
| 74 |
switch tt { |
| 75 |
case xml.ErrorToken: |
| 76 |
if l.Err() != io.EOF { |
| 77 |
fmt.Println("Error on line", l.Line(), ":", l.Err()) |
| 78 |
} |
| 79 |
return |
| 80 |
case xml.StartTagToken: |
| 81 |
fmt.Println("Tag", string(data)) |
| 82 |
for { |
| 83 |
ttAttr, dataAttr := l.Next() |
| 84 |
if ttAttr != xml.AttributeToken { |
| 85 |
break |
| 86 |
} |
| 87 |
|
| 88 |
key := dataAttr |
| 89 |
val := l.AttrVal() |
| 90 |
fmt.Println("Attribute", string(key), "=", string(val)) |
| 91 |
} |
| 92 |
// ... |
| 93 |
} |
| 94 |
} |
| 95 |
} |
| 96 |
``` |
| 97 |
|
| 98 |
## License |
| 99 |
Released under the [MIT license](https://github.com/tdewolff/parse/blob/master/LICENSE.md). |
| 100 |
|
| 101 |
[1]: http://golang.org/ "Go Language" |