Documentation
¶
Overview ¶
Package xmlutil provides XML-specific helpers, including XML-style charset detection and declaration parsing.
It is compatible with the XML spec for most documents, but does not strictly adhere to it and is generally a bit more lenient (since this library is primarily designed for the HTML spec).
The helpers are for reading XML documents with a github.com/pgaskin/htmlstream.Reader in github.com/pgaskin/htmlstream.XML mode, and writing them. A Reader requires UTF-8 input, or input in another encoding in which ASCII characters have their ASCII bytes, so documents in other encodings (e.g., UTF-16) must be decoded first (see Input in the htmlstream package documentation). CheckWellFormed checks that a document is well-formed, which the Reader doesn't.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrNoDecl = errors.New("xmlutil: no XML declaration")
ErrNoDecl is returned by ParseDecl for input which doesn't start with an XML declaration.
Functions ¶
func AppendDecl ¶
AppendDecl appends an XML declaration with the non-empty values of d to dst, in double quotes, e.g., <?xml version="1.0" encoding="UTF-8"?>. The values are written as-is and aren't checked (see ParseDecl for their syntax). An XML declaration must have a version, and a text declaration an encoding.
Example ¶
After decoding a document to UTF-8, a Transformer can replace the XML declaration, which names the original encoding.
package main
import (
"os"
"strings"
"github.com/pgaskin/htmlstream"
"github.com/pgaskin/htmlstream/xmlutil"
)
func main() {
const doc = "<?xml version='1.0' encoding='ISO-8859-1'?>\n<p>café</p>" // decoded
x := htmlstream.NewTransformer(os.Stdout, strings.NewReader(doc))
x.SetMode(htmlstream.XML)
for x.Next() {
tok := x.Token()
if tok.Pos() != 0 || tok.Kind() != htmlstream.ProcInst {
continue
}
d, _, err := xmlutil.ParseDecl(tok.Raw())
if err != nil {
panic(err)
}
d.Encoding = "UTF-8"
if err := x.Replace(xmlutil.AppendDecl(nil, d)); err != nil {
panic(err)
}
}
if err := x.Close(); err != nil {
panic(err)
}
}
Output: <?xml version="1.0" encoding="UTF-8"?> <p>café</p>
func AppendEscape ¶
AppendEscape appends s to dst, escaped for use as text or as a double-quoted attribute value in XML: &, <, >, " and tabs, newlines and carriage returns are written as character references. XML parsers then read it back unchanged: references aren't changed by end-of-line handling, which converts carriage returns to newlines, or by attribute-value normalization, which converts whitespace in attribute values to spaces, and escaping > keeps "]]>" out of character data. ' isn't escaped, so attribute values must be in double quotes. Characters XML doesn't allow aren't replaced (see github.com/pgaskin/htmlstream.AppendXMLChars and github.com/pgaskin/htmlstream.ValidXMLChars). It follows XML 1.0: NEL and U+2028, which are line ends in XML 1.1 documents, aren't escaped, and neither are U+007F to U+009F, which XML 1.1 only allows as character references (see Modes in the htmlstream package documentation).
Example ¶
AppendEscape escapes text and attribute values so XML parsers read them back unchanged, including whitespace in attribute values.
package main
import (
"fmt"
"github.com/pgaskin/htmlstream/xmlutil"
)
func main() {
const value = "a < b && c\td\r\ne"
b := []byte(`<p title="`)
b = xmlutil.AppendEscape(b, value)
b = append(b, `">`...)
b = xmlutil.AppendEscape(b, value)
b = append(b, "</p>"...)
fmt.Println(string(b))
}
Output: <p title="a < b && c	d e">a < b && c	d e</p>
func CheckWellFormed ¶ added in v0.0.2
CheckWellFormed reads an XML document from r and checks that it is well-formed and namespace-well-formed. It returns nil if it is, a *htmlstream.SyntaxError at the first token which isn't, or an error from r or the Reader (e.g., htmlstream.ErrTokenTooLarge).
It reads the document with an htmlstream.Reader in htmlstream.XML mode with the default limits, and checks each token as it is read: the syntax of tags, references, comments, processing instructions, the XML declaration and the doctype, the characters (see htmlstream.ValidXMLChars) and names (see htmlstream.ValidXMLName), the nesting of the elements, that there is a single root element, with only whitespace, comments, processing instructions and a doctype around it, and the namespace constraints. An element nested past the Reader's stack limits (htmlstream.DefaultMaxDepth and htmlstream.DefaultMaxStackBytes) is an error, since its end tag isn't matched with its start tag.
The doctype isn't processed: its internal subset isn't checked, and with an internal subset, or an external ID without standalone="yes" in the XML declaration, references to entities other than lt, gt, amp, apos and quot are accepted without checking that the entities are declared and that their replacement text is well-formed. External entities aren't read. Names follow the Fourth Edition of XML 1.0, like ValidXMLName, so names with characters only allowed since the Fifth Edition are errors. XML 1.1 documents are checked with the rules of XML 1.0.
The input must be UTF-8 (see the package documentation): documents in other encodings must be decoded first, and the encoding declaration isn't checked against the input.
Types ¶
type Decl ¶
type Decl struct {
Version string // e.g., "1.0"
Encoding string // the encoding name, e.g., "UTF-8"
Standalone string // "yes" or "no"
}
Decl is an XML declaration, or the text declaration of an external parsed entity, which has no version or standalone declaration. Its values are as written in the declaration, or empty if they are missing.
func ParseDecl ¶
ParseDecl parses the XML declaration at the start of b, and returns it and its length. b is, e.g., the start of a document, or the Raw of a github.com/pgaskin/htmlstream.ProcInst token with the target "xml" (at the start of the document, the only place where an XML declaration is allowed; elsewhere, XML reserves the target). It returns ErrNoDecl if b doesn't start with "<?xml" followed by XML whitespace or "?>" (the target is case-sensitive).
The declaration follows the XMLDecl production of XML 1.0: the version, encoding and standalone pseudo-attributes, in that order, with whitespace before each, "=" between the name and the value (with optional whitespace around it), and the value in single or double quotes. The version must match VersionNum (e.g., "1.0"), the encoding EncName (e.g., "UTF-8"), and standalone must be "yes" or "no" (SDDecl). A declaration without a version is accepted if it has an encoding and no standalone, like the text declarations of external parsed entities (TextDecl).
For a declaration which doesn't follow the syntax, it returns a *DeclError for the first difference, along with the pseudo-attributes it read and the length of the declaration: it reads them in any order and with unquoted values (up to the next whitespace or "?>"), and skips unknown ones. For a declaration cut off by the end of b, the length is 0.
Example ¶
ParseDecl reads malformed declarations too, returning an error for the first difference from the syntax.
package main
import (
"fmt"
"github.com/pgaskin/htmlstream/xmlutil"
)
func main() {
for _, decl := range []string{
`<?xml version="1.0" encoding="UTF-8" standalone="no"?>`,
`<?xml encoding='EUC-JP'?>`,
`<?xml version=1.0 encoding=latin1?>`,
} {
d, n, err := xmlutil.ParseDecl([]byte(decl))
fmt.Printf("%+v %d %v\n", d, n, err)
}
}
Output: {Version:1.0 Encoding:UTF-8 Standalone:no} 54 <nil> {Version: Encoding:EUC-JP Standalone:} 25 <nil> {Version:1.0 Encoding:latin1 Standalone:} 35 xmlutil: XML declaration: value of "version" isn't quoted at offset 14
type DeclError ¶
type DeclError struct {
Offset int // the offset of the first byte which doesn't follow the syntax
Msg string // what is wrong
}
DeclError is returned by ParseDecl for an XML declaration which doesn't follow the syntax of XML declarations and text declarations.
type Encoding ¶
type Encoding struct {
// Name is the name of the encoding: the name the [Encoding Standard]
// gives it (e.g., "UTF-8", "UTF-16LE" or "windows-1252"), which
// golang.org/x/text/encoding/htmlindex.Get accepts, or "UTF-32BE" or
// "UTF-32LE", which aren't in the Encoding Standard (see
// golang.org/x/text/encoding/unicode/utf32). It is empty if the encoding
// isn't known: for EBCDIC (see Declared, e.g., with
// golang.org/x/text/encoding/ianaindex.IANA), 32-bit encodings with
// unusual byte orders, and ASCII-compatible encodings declared with a
// name which isn't a label of the Encoding Standard.
Name string
// Declared is the encoding name in the XML declaration, as written, or
// empty if there is none. It is read from declarations which don't
// follow the syntax too (see [ParseDecl]).
Declared string
// BOM is the length of the byte order mark at the start of the document,
// or 0 if there is none. Some decoders keep it as a U+FEFF character
// (e.g., those of htmlindex), so it can be skipped before decoding.
BOM int
}
Encoding is the character encoding of an XML document detected by DetectEncoding.
func DetectEncoding ¶
DetectEncoding detects the character encoding of an XML document (or external parsed entity) starting with head, as described by XML 1.0 for documents without external encoding information (Appendix F.1). head should have at least the XML declaration (e.g., the first 1024 bytes of the document, or the whole document if it is shorter). A declaration cut off by the end of head is read up to the end.
The first four bytes give the byte order mark or the encoding family:
- With a byte order mark (EF BB BF, FE FF or FF FE, and for UCS-4, 00 00 FE FF, FF FE 00 00, 00 00 FF FE or FE FF 00 00), the encoding is UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, UTF-32LE or unknown (UCS-4 with the byte orders 2143 or 3412).
- Without one, "<?" in a 16-bit or 32-bit encoding gives UTF-16BE, UTF-16LE, UTF-32BE, UTF-32LE or unknown (the unusual byte orders), and "<?xm" in EBCDIC (4C 6F A7 94) gives an unknown encoding, which the declaration names (e.g., IBM037).
- Otherwise, the encoding is ASCII-compatible: the one named by the XML declaration, or UTF-8 without a declaration or encoding name.
Encoding names are looked up like get an encoding in the Encoding Standard, which browsers use for XML documents too: they are matched ASCII case-insensitively after removing leading and trailing whitespace, and some are aliases of other encodings (e.g., ISO-8859-1 and US-ASCII are windows-1252). XML 1.0 refers to the encodings registered with IANA instead (4.3.3), which golang.org/x/text/encoding/ianaindex.IANA looks up (e.g., from Encoding.Declared). As in the steps to change the encoding of the HTML Standard, UTF-16 (or UTF-16BE or UTF-16LE) declared in an ASCII-compatible document gives UTF-8. Some names (e.g., ISO-2022-KR) give the replacement encoding, which decodes any non-empty input to a single U+FFFD.
DetectEncoding differs from XML processors in these ways:
- The declared encoding isn't checked against the encoding detected from the byte order mark or the first bytes, which XML 1.0 requires. With a byte order mark or a 16-bit or 32-bit encoding, the declaration only sets Encoding.Declared.
- XML declarations which don't follow the syntax, a fatal error for XML processors, are read like ParseDecl does.
- It doesn't take external encoding information, like the charset parameter of the Content-Type header, which takes precedence over the declaration, but not over a byte order mark (RFC 7303).
Browsers differ further: they support only the encodings of the Encoding Standard (not UTF-32, EBCDIC or UCS-4), and read FF FE 00 00 as a UTF-16LE byte order mark. For an XML declaration in an HTML document, github.com/pgaskin/htmlstream/htmlutil.PrescanCharset follows the HTML Standard instead, which looks for "encoding" anywhere before the first ">", and only in ASCII-compatible encodings.
For example, with golang.org/x/text/encoding/htmlindex, golang.org/x/text/encoding/unicode/utf32 (for the UTF-32 encodings, which htmlindex doesn't have) and golang.org/x/text/transform:
br := bufio.NewReader(r)
head, _ := br.Peek(1024) // the whole input if it is shorter
e := xmlutil.DetectEncoding(head)
var enc encoding.Encoding
switch e.Name {
case "":
return fmt.Errorf("unsupported encoding %q", e.Declared)
case "UTF-32BE":
enc = utf32.UTF32(utf32.BigEndian, utf32.IgnoreBOM)
case "UTF-32LE":
enc = utf32.UTF32(utf32.LittleEndian, utf32.IgnoreBOM)
default:
var err error
if enc, err = htmlindex.Get(e.Name); err != nil {
return err
}
}
br.Discard(e.BOM)
rd := htmlstream.NewReader(transform.NewReader(br, enc.NewDecoder()))
rd.SetMode(htmlstream.XML)
The XML declaration of a document decoded to UTF-8 names the original encoding, so a Transformer writing the document can replace it (see AppendDecl).
Example ¶
DetectEncoding gives the encoding of a document from its byte order mark, its first bytes and its XML declaration.
package main
import (
"fmt"
"github.com/pgaskin/htmlstream/xmlutil"
)
func main() {
for _, head := range []string{
`<?xml version="1.0"?><a/>`,
`<?xml version="1.0" encoding="ISO-8859-1"?><a/>`,
`<?xml version="1.0" encoding="x-custom"?><a/>`,
"\xEF\xBB\xBF<a/>",
"\xFF\xFE<\x00?\x00x\x00m\x00l\x00 \x00e\x00n\x00c\x00o\x00d\x00i\x00n\x00g\x00=\x00'\x00U\x00T\x00F\x00-\x001\x006\x00'\x00?\x00>\x00",
} {
fmt.Printf("%+v\n", xmlutil.DetectEncoding([]byte(head)))
}
}
Output: {Name:UTF-8 Declared: BOM:0} {Name:windows-1252 Declared:ISO-8859-1 BOM:0} {Name: Declared:x-custom BOM:0} {Name:UTF-8 Declared: BOM:3} {Name:UTF-16LE Declared:UTF-16 BOM:2}
func (Encoding) ASCIICompatible ¶
ASCIICompatible reports whether a github.com/pgaskin/htmlstream.Reader can read a document in the encoding without decoding it first. It is best-effort, from Encoding.Name: it reports true for the encodings of the Encoding Standard in which bytes 0x00 to 0x7F outside multi-byte characters are ASCII characters (which it calls ASCII-compatible in its security background): UTF-8, the single-byte encodings (e.g., windows-1252), EUC-JP, Shift_JIS, EUC-KR, Big5, GBK and gb18030. It reports false for UTF-16BE, UTF-16LE, UTF-32BE, UTF-32LE, ISO-2022-JP (whose escape sequences switch to modes in which ASCII bytes are parts of JIS characters), replacement, and empty or unknown names, including those of ASCII-compatible encodings outside the Encoding Standard.
A Reader reads a document in an ASCII-compatible encoding with the differences described in Input in the htmlstream package documentation. In Shift_JIS, Big5, GBK and gb18030, the second byte of a character can be that of an ASCII character from "@" to "~" (0x40 to 0x7E: letters, "[", "]", "\", "^", "_", "`", "{", "|", "}", "~" and "@"), in EUC-KR that of a letter, and in gb18030 the second and fourth bytes of a four-byte character are those of ASCII digits; none of them is a markup character or whitespace. Decoded text has character references and U+FFFD replacements as UTF-8, mixed with the undecoded bytes.
Example ¶
ASCIICompatible reports whether a Reader can read a document without decoding it first.
package main
import (
"fmt"
"github.com/pgaskin/htmlstream/xmlutil"
)
func main() {
for _, head := range []string{
`<?xml version="1.0" encoding="Shift_JIS"?>`,
`<?xml version="1.0" encoding="ISO-2022-JP"?>`,
"\xFE\xFF\x00<\x00?\x00x\x00m\x00l",
} {
e := xmlutil.DetectEncoding([]byte(head))
fmt.Println(e.Name, e.ASCIICompatible())
}
}
Output: Shift_JIS true ISO-2022-JP false UTF-16BE false