...
Run Format

Source file src/encoding/xml/xml.go

     1	// Copyright 2009 The Go Authors. All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	// Package xml implements a simple XML 1.0 parser that
     6	// understands XML name spaces.
     7	package xml
     8	
     9	// References:
    10	//    Annotated XML spec: http://www.xml.com/axml/testaxml.htm
    11	//    XML name spaces: http://www.w3.org/TR/REC-xml-names/
    12	
    13	// TODO(rsc):
    14	//	Test error handling.
    15	
    16	import (
    17		"bufio"
    18		"bytes"
    19		"errors"
    20		"fmt"
    21		"io"
    22		"strconv"
    23		"strings"
    24		"unicode"
    25		"unicode/utf8"
    26	)
    27	
    28	// A SyntaxError represents a syntax error in the XML input stream.
    29	type SyntaxError struct {
    30		Msg  string
    31		Line int
    32	}
    33	
    34	func (e *SyntaxError) Error() string {
    35		return "XML syntax error on line " + strconv.Itoa(e.Line) + ": " + e.Msg
    36	}
    37	
    38	// A Name represents an XML name (Local) annotated
    39	// with a name space identifier (Space).
    40	// In tokens returned by Decoder.Token, the Space identifier
    41	// is given as a canonical URL, not the short prefix used
    42	// in the document being parsed.
    43	type Name struct {
    44		Space, Local string
    45	}
    46	
    47	// An Attr represents an attribute in an XML element (Name=Value).
    48	type Attr struct {
    49		Name  Name
    50		Value string
    51	}
    52	
    53	// A Token is an interface holding one of the token types:
    54	// StartElement, EndElement, CharData, Comment, ProcInst, or Directive.
    55	type Token interface{}
    56	
    57	// A StartElement represents an XML start element.
    58	type StartElement struct {
    59		Name Name
    60		Attr []Attr
    61	}
    62	
    63	func (e StartElement) Copy() StartElement {
    64		attrs := make([]Attr, len(e.Attr))
    65		copy(attrs, e.Attr)
    66		e.Attr = attrs
    67		return e
    68	}
    69	
    70	// End returns the corresponding XML end element.
    71	func (e StartElement) End() EndElement {
    72		return EndElement{e.Name}
    73	}
    74	
    75	// An EndElement represents an XML end element.
    76	type EndElement struct {
    77		Name Name
    78	}
    79	
    80	// A CharData represents XML character data (raw text),
    81	// in which XML escape sequences have been replaced by
    82	// the characters they represent.
    83	type CharData []byte
    84	
    85	func makeCopy(b []byte) []byte {
    86		b1 := make([]byte, len(b))
    87		copy(b1, b)
    88		return b1
    89	}
    90	
    91	func (c CharData) Copy() CharData { return CharData(makeCopy(c)) }
    92	
    93	// A Comment represents an XML comment of the form <!--comment-->.
    94	// The bytes do not include the <!-- and --> comment markers.
    95	type Comment []byte
    96	
    97	func (c Comment) Copy() Comment { return Comment(makeCopy(c)) }
    98	
    99	// A ProcInst represents an XML processing instruction of the form <?target inst?>
   100	type ProcInst struct {
   101		Target string
   102		Inst   []byte
   103	}
   104	
   105	func (p ProcInst) Copy() ProcInst {
   106		p.Inst = makeCopy(p.Inst)
   107		return p
   108	}
   109	
   110	// A Directive represents an XML directive of the form <!text>.
   111	// The bytes do not include the <! and > markers.
   112	type Directive []byte
   113	
   114	func (d Directive) Copy() Directive { return Directive(makeCopy(d)) }
   115	
   116	// CopyToken returns a copy of a Token.
   117	func CopyToken(t Token) Token {
   118		switch v := t.(type) {
   119		case CharData:
   120			return v.Copy()
   121		case Comment:
   122			return v.Copy()
   123		case Directive:
   124			return v.Copy()
   125		case ProcInst:
   126			return v.Copy()
   127		case StartElement:
   128			return v.Copy()
   129		}
   130		return t
   131	}
   132	
   133	// A Decoder represents an XML parser reading a particular input stream.
   134	// The parser assumes that its input is encoded in UTF-8.
   135	type Decoder struct {
   136		// Strict defaults to true, enforcing the requirements
   137		// of the XML specification.
   138		// If set to false, the parser allows input containing common
   139		// mistakes:
   140		//	* If an element is missing an end tag, the parser invents
   141		//	  end tags as necessary to keep the return values from Token
   142		//	  properly balanced.
   143		//	* In attribute values and character data, unknown or malformed
   144		//	  character entities (sequences beginning with &) are left alone.
   145		//
   146		// Setting:
   147		//
   148		//	d.Strict = false;
   149		//	d.AutoClose = HTMLAutoClose;
   150		//	d.Entity = HTMLEntity
   151		//
   152		// creates a parser that can handle typical HTML.
   153		//
   154		// Strict mode does not enforce the requirements of the XML name spaces TR.
   155		// In particular it does not reject name space tags using undefined prefixes.
   156		// Such tags are recorded with the unknown prefix as the name space URL.
   157		Strict bool
   158	
   159		// When Strict == false, AutoClose indicates a set of elements to
   160		// consider closed immediately after they are opened, regardless
   161		// of whether an end element is present.
   162		AutoClose []string
   163	
   164		// Entity can be used to map non-standard entity names to string replacements.
   165		// The parser behaves as if these standard mappings are present in the map,
   166		// regardless of the actual map content:
   167		//
   168		//	"lt": "<",
   169		//	"gt": ">",
   170		//	"amp": "&",
   171		//	"apos": "'",
   172		//	"quot": `"`,
   173		Entity map[string]string
   174	
   175		// CharsetReader, if non-nil, defines a function to generate
   176		// charset-conversion readers, converting from the provided
   177		// non-UTF-8 charset into UTF-8. If CharsetReader is nil or
   178		// returns an error, parsing stops with an error. One of the
   179		// the CharsetReader's result values must be non-nil.
   180		CharsetReader func(charset string, input io.Reader) (io.Reader, error)
   181	
   182		// DefaultSpace sets the default name space used for unadorned tags,
   183		// as if the entire XML stream were wrapped in an element containing
   184		// the attribute xmlns="DefaultSpace".
   185		DefaultSpace string
   186	
   187		r              io.ByteReader
   188		buf            bytes.Buffer
   189		saved          *bytes.Buffer
   190		stk            *stack
   191		free           *stack
   192		needClose      bool
   193		toClose        Name
   194		nextToken      Token
   195		nextByte       int
   196		ns             map[string]string
   197		err            error
   198		line           int
   199		offset         int64
   200		unmarshalDepth int
   201	}
   202	
   203	// NewDecoder creates a new XML parser reading from r.
   204	// If r does not implement io.ByteReader, NewDecoder will
   205	// do its own buffering.
   206	func NewDecoder(r io.Reader) *Decoder {
   207		d := &Decoder{
   208			ns:       make(map[string]string),
   209			nextByte: -1,
   210			line:     1,
   211			Strict:   true,
   212		}
   213		d.switchToReader(r)
   214		return d
   215	}
   216	
   217	// Token returns the next XML token in the input stream.
   218	// At the end of the input stream, Token returns nil, io.EOF.
   219	//
   220	// Slices of bytes in the returned token data refer to the
   221	// parser's internal buffer and remain valid only until the next
   222	// call to Token.  To acquire a copy of the bytes, call CopyToken
   223	// or the token's Copy method.
   224	//
   225	// Token expands self-closing elements such as <br/>
   226	// into separate start and end elements returned by successive calls.
   227	//
   228	// Token guarantees that the StartElement and EndElement
   229	// tokens it returns are properly nested and matched:
   230	// if Token encounters an unexpected end element
   231	// or EOF before all expected end elements,
   232	// it will return an error.
   233	//
   234	// Token implements XML name spaces as described by
   235	// http://www.w3.org/TR/REC-xml-names/.  Each of the
   236	// Name structures contained in the Token has the Space
   237	// set to the URL identifying its name space when known.
   238	// If Token encounters an unrecognized name space prefix,
   239	// it uses the prefix as the Space rather than report an error.
   240	func (d *Decoder) Token() (t Token, err error) {
   241		if d.stk != nil && d.stk.kind == stkEOF {
   242			err = io.EOF
   243			return
   244		}
   245		if d.nextToken != nil {
   246			t = d.nextToken
   247			d.nextToken = nil
   248		} else if t, err = d.rawToken(); err != nil {
   249			if err == io.EOF && d.stk != nil && d.stk.kind != stkEOF {
   250				err = d.syntaxError("unexpected EOF")
   251			}
   252			return
   253		}
   254	
   255		if !d.Strict {
   256			if t1, ok := d.autoClose(t); ok {
   257				d.nextToken = t
   258				t = t1
   259			}
   260		}
   261		switch t1 := t.(type) {
   262		case StartElement:
   263			// In XML name spaces, the translations listed in the
   264			// attributes apply to the element name and
   265			// to the other attribute names, so process
   266			// the translations first.
   267			for _, a := range t1.Attr {
   268				if a.Name.Space == "xmlns" {
   269					v, ok := d.ns[a.Name.Local]
   270					d.pushNs(a.Name.Local, v, ok)
   271					d.ns[a.Name.Local] = a.Value
   272				}
   273				if a.Name.Space == "" && a.Name.Local == "xmlns" {
   274					// Default space for untagged names
   275					v, ok := d.ns[""]
   276					d.pushNs("", v, ok)
   277					d.ns[""] = a.Value
   278				}
   279			}
   280	
   281			d.translate(&t1.Name, true)
   282			for i := range t1.Attr {
   283				d.translate(&t1.Attr[i].Name, false)
   284			}
   285			d.pushElement(t1.Name)
   286			t = t1
   287	
   288		case EndElement:
   289			d.translate(&t1.Name, true)
   290			if !d.popElement(&t1) {
   291				return nil, d.err
   292			}
   293			t = t1
   294		}
   295		return
   296	}
   297	
   298	const xmlURL = "http://www.w3.org/XML/1998/namespace"
   299	
   300	// Apply name space translation to name n.
   301	// The default name space (for Space=="")
   302	// applies only to element names, not to attribute names.
   303	func (d *Decoder) translate(n *Name, isElementName bool) {
   304		switch {
   305		case n.Space == "xmlns":
   306			return
   307		case n.Space == "" && !isElementName:
   308			return
   309		case n.Space == "xml":
   310			n.Space = xmlURL
   311		case n.Space == "" && n.Local == "xmlns":
   312			return
   313		}
   314		if v, ok := d.ns[n.Space]; ok {
   315			n.Space = v
   316		} else if n.Space == "" {
   317			n.Space = d.DefaultSpace
   318		}
   319	}
   320	
   321	func (d *Decoder) switchToReader(r io.Reader) {
   322		// Get efficient byte at a time reader.
   323		// Assume that if reader has its own
   324		// ReadByte, it's efficient enough.
   325		// Otherwise, use bufio.
   326		if rb, ok := r.(io.ByteReader); ok {
   327			d.r = rb
   328		} else {
   329			d.r = bufio.NewReader(r)
   330		}
   331	}
   332	
   333	// Parsing state - stack holds old name space translations
   334	// and the current set of open elements.  The translations to pop when
   335	// ending a given tag are *below* it on the stack, which is
   336	// more work but forced on us by XML.
   337	type stack struct {
   338		next *stack
   339		kind int
   340		name Name
   341		ok   bool
   342	}
   343	
   344	const (
   345		stkStart = iota
   346		stkNs
   347		stkEOF
   348	)
   349	
   350	func (d *Decoder) push(kind int) *stack {
   351		s := d.free
   352		if s != nil {
   353			d.free = s.next
   354		} else {
   355			s = new(stack)
   356		}
   357		s.next = d.stk
   358		s.kind = kind
   359		d.stk = s
   360		return s
   361	}
   362	
   363	func (d *Decoder) pop() *stack {
   364		s := d.stk
   365		if s != nil {
   366			d.stk = s.next
   367			s.next = d.free
   368			d.free = s
   369		}
   370		return s
   371	}
   372	
   373	// Record that after the current element is finished
   374	// (that element is already pushed on the stack)
   375	// Token should return EOF until popEOF is called.
   376	func (d *Decoder) pushEOF() {
   377		// Walk down stack to find Start.
   378		// It might not be the top, because there might be stkNs
   379		// entries above it.
   380		start := d.stk
   381		for start.kind != stkStart {
   382			start = start.next
   383		}
   384		// The stkNs entries below a start are associated with that
   385		// element too; skip over them.
   386		for start.next != nil && start.next.kind == stkNs {
   387			start = start.next
   388		}
   389		s := d.free
   390		if s != nil {
   391			d.free = s.next
   392		} else {
   393			s = new(stack)
   394		}
   395		s.kind = stkEOF
   396		s.next = start.next
   397		start.next = s
   398	}
   399	
   400	// Undo a pushEOF.
   401	// The element must have been finished, so the EOF should be at the top of the stack.
   402	func (d *Decoder) popEOF() bool {
   403		if d.stk == nil || d.stk.kind != stkEOF {
   404			return false
   405		}
   406		d.pop()
   407		return true
   408	}
   409	
   410	// Record that we are starting an element with the given name.
   411	func (d *Decoder) pushElement(name Name) {
   412		s := d.push(stkStart)
   413		s.name = name
   414	}
   415	
   416	// Record that we are changing the value of ns[local].
   417	// The old value is url, ok.
   418	func (d *Decoder) pushNs(local string, url string, ok bool) {
   419		s := d.push(stkNs)
   420		s.name.Local = local
   421		s.name.Space = url
   422		s.ok = ok
   423	}
   424	
   425	// Creates a SyntaxError with the current line number.
   426	func (d *Decoder) syntaxError(msg string) error {
   427		return &SyntaxError{Msg: msg, Line: d.line}
   428	}
   429	
   430	// Record that we are ending an element with the given name.
   431	// The name must match the record at the top of the stack,
   432	// which must be a pushElement record.
   433	// After popping the element, apply any undo records from
   434	// the stack to restore the name translations that existed
   435	// before we saw this element.
   436	func (d *Decoder) popElement(t *EndElement) bool {
   437		s := d.pop()
   438		name := t.Name
   439		switch {
   440		case s == nil || s.kind != stkStart:
   441			d.err = d.syntaxError("unexpected end element </" + name.Local + ">")
   442			return false
   443		case s.name.Local != name.Local:
   444			if !d.Strict {
   445				d.needClose = true
   446				d.toClose = t.Name
   447				t.Name = s.name
   448				return true
   449			}
   450			d.err = d.syntaxError("element <" + s.name.Local + "> closed by </" + name.Local + ">")
   451			return false
   452		case s.name.Space != name.Space:
   453			d.err = d.syntaxError("element <" + s.name.Local + "> in space " + s.name.Space +
   454				"closed by </" + name.Local + "> in space " + name.Space)
   455			return false
   456		}
   457	
   458		// Pop stack until a Start or EOF is on the top, undoing the
   459		// translations that were associated with the element we just closed.
   460		for d.stk != nil && d.stk.kind != stkStart && d.stk.kind != stkEOF {
   461			s := d.pop()
   462			if s.ok {
   463				d.ns[s.name.Local] = s.name.Space
   464			} else {
   465				delete(d.ns, s.name.Local)
   466			}
   467		}
   468	
   469		return true
   470	}
   471	
   472	// If the top element on the stack is autoclosing and
   473	// t is not the end tag, invent the end tag.
   474	func (d *Decoder) autoClose(t Token) (Token, bool) {
   475		if d.stk == nil || d.stk.kind != stkStart {
   476			return nil, false
   477		}
   478		name := strings.ToLower(d.stk.name.Local)
   479		for _, s := range d.AutoClose {
   480			if strings.ToLower(s) == name {
   481				// This one should be auto closed if t doesn't close it.
   482				et, ok := t.(EndElement)
   483				if !ok || et.Name.Local != name {
   484					return EndElement{d.stk.name}, true
   485				}
   486				break
   487			}
   488		}
   489		return nil, false
   490	}
   491	
   492	var errRawToken = errors.New("xml: cannot use RawToken from UnmarshalXML method")
   493	
   494	// RawToken is like Token but does not verify that
   495	// start and end elements match and does not translate
   496	// name space prefixes to their corresponding URLs.
   497	func (d *Decoder) RawToken() (Token, error) {
   498		if d.unmarshalDepth > 0 {
   499			return nil, errRawToken
   500		}
   501		return d.rawToken()
   502	}
   503	
   504	func (d *Decoder) rawToken() (Token, error) {
   505		if d.err != nil {
   506			return nil, d.err
   507		}
   508		if d.needClose {
   509			// The last element we read was self-closing and
   510			// we returned just the StartElement half.
   511			// Return the EndElement half now.
   512			d.needClose = false
   513			return EndElement{d.toClose}, nil
   514		}
   515	
   516		b, ok := d.getc()
   517		if !ok {
   518			return nil, d.err
   519		}
   520	
   521		if b != '<' {
   522			// Text section.
   523			d.ungetc(b)
   524			data := d.text(-1, false)
   525			if data == nil {
   526				return nil, d.err
   527			}
   528			return CharData(data), nil
   529		}
   530	
   531		if b, ok = d.mustgetc(); !ok {
   532			return nil, d.err
   533		}
   534		switch b {
   535		case '/':
   536			// </: End element
   537			var name Name
   538			if name, ok = d.nsname(); !ok {
   539				if d.err == nil {
   540					d.err = d.syntaxError("expected element name after </")
   541				}
   542				return nil, d.err
   543			}
   544			d.space()
   545			if b, ok = d.mustgetc(); !ok {
   546				return nil, d.err
   547			}
   548			if b != '>' {
   549				d.err = d.syntaxError("invalid characters between </" + name.Local + " and >")
   550				return nil, d.err
   551			}
   552			return EndElement{name}, nil
   553	
   554		case '?':
   555			// <?: Processing instruction.
   556			var target string
   557			if target, ok = d.name(); !ok {
   558				if d.err == nil {
   559					d.err = d.syntaxError("expected target name after <?")
   560				}
   561				return nil, d.err
   562			}
   563			d.space()
   564			d.buf.Reset()
   565			var b0 byte
   566			for {
   567				if b, ok = d.mustgetc(); !ok {
   568					return nil, d.err
   569				}
   570				d.buf.WriteByte(b)
   571				if b0 == '?' && b == '>' {
   572					break
   573				}
   574				b0 = b
   575			}
   576			data := d.buf.Bytes()
   577			data = data[0 : len(data)-2] // chop ?>
   578	
   579			if target == "xml" {
   580				content := string(data)
   581				ver := procInst("version", content)
   582				if ver != "" && ver != "1.0" {
   583					d.err = fmt.Errorf("xml: unsupported version %q; only version 1.0 is supported", ver)
   584					return nil, d.err
   585				}
   586				enc := procInst("encoding", content)
   587				if enc != "" && enc != "utf-8" && enc != "UTF-8" && !strings.EqualFold(enc, "utf-8") {
   588					if d.CharsetReader == nil {
   589						d.err = fmt.Errorf("xml: encoding %q declared but Decoder.CharsetReader is nil", enc)
   590						return nil, d.err
   591					}
   592					newr, err := d.CharsetReader(enc, d.r.(io.Reader))
   593					if err != nil {
   594						d.err = fmt.Errorf("xml: opening charset %q: %v", enc, err)
   595						return nil, d.err
   596					}
   597					if newr == nil {
   598						panic("CharsetReader returned a nil Reader for charset " + enc)
   599					}
   600					d.switchToReader(newr)
   601				}
   602			}
   603			return ProcInst{target, data}, nil
   604	
   605		case '!':
   606			// <!: Maybe comment, maybe CDATA.
   607			if b, ok = d.mustgetc(); !ok {
   608				return nil, d.err
   609			}
   610			switch b {
   611			case '-': // <!-
   612				// Probably <!-- for a comment.
   613				if b, ok = d.mustgetc(); !ok {
   614					return nil, d.err
   615				}
   616				if b != '-' {
   617					d.err = d.syntaxError("invalid sequence <!- not part of <!--")
   618					return nil, d.err
   619				}
   620				// Look for terminator.
   621				d.buf.Reset()
   622				var b0, b1 byte
   623				for {
   624					if b, ok = d.mustgetc(); !ok {
   625						return nil, d.err
   626					}
   627					d.buf.WriteByte(b)
   628					if b0 == '-' && b1 == '-' {
   629						if b != '>' {
   630							d.err = d.syntaxError(
   631								`invalid sequence "--" not allowed in comments`)
   632							return nil, d.err
   633						}
   634						break
   635					}
   636					b0, b1 = b1, b
   637				}
   638				data := d.buf.Bytes()
   639				data = data[0 : len(data)-3] // chop -->
   640				return Comment(data), nil
   641	
   642			case '[': // <![
   643				// Probably <![CDATA[.
   644				for i := 0; i < 6; i++ {
   645					if b, ok = d.mustgetc(); !ok {
   646						return nil, d.err
   647					}
   648					if b != "CDATA["[i] {
   649						d.err = d.syntaxError("invalid <![ sequence")
   650						return nil, d.err
   651					}
   652				}
   653				// Have <![CDATA[.  Read text until ]]>.
   654				data := d.text(-1, true)
   655				if data == nil {
   656					return nil, d.err
   657				}
   658				return CharData(data), nil
   659			}
   660	
   661			// Probably a directive: <!DOCTYPE ...>, <!ENTITY ...>, etc.
   662			// We don't care, but accumulate for caller. Quoted angle
   663			// brackets do not count for nesting.
   664			d.buf.Reset()
   665			d.buf.WriteByte(b)
   666			inquote := uint8(0)
   667			depth := 0
   668			for {
   669				if b, ok = d.mustgetc(); !ok {
   670					return nil, d.err
   671				}
   672				if inquote == 0 && b == '>' && depth == 0 {
   673					break
   674				}
   675			HandleB:
   676				d.buf.WriteByte(b)
   677				switch {
   678				case b == inquote:
   679					inquote = 0
   680	
   681				case inquote != 0:
   682					// in quotes, no special action
   683	
   684				case b == '\'' || b == '"':
   685					inquote = b
   686	
   687				case b == '>' && inquote == 0:
   688					depth--
   689	
   690				case b == '<' && inquote == 0:
   691					// Look for <!-- to begin comment.
   692					s := "!--"
   693					for i := 0; i < len(s); i++ {
   694						if b, ok = d.mustgetc(); !ok {
   695							return nil, d.err
   696						}
   697						if b != s[i] {
   698							for j := 0; j < i; j++ {
   699								d.buf.WriteByte(s[j])
   700							}
   701							depth++
   702							goto HandleB
   703						}
   704					}
   705	
   706					// Remove < that was written above.
   707					d.buf.Truncate(d.buf.Len() - 1)
   708	
   709					// Look for terminator.
   710					var b0, b1 byte
   711					for {
   712						if b, ok = d.mustgetc(); !ok {
   713							return nil, d.err
   714						}
   715						if b0 == '-' && b1 == '-' && b == '>' {
   716							break
   717						}
   718						b0, b1 = b1, b
   719					}
   720				}
   721			}
   722			return Directive(d.buf.Bytes()), nil
   723		}
   724	
   725		// Must be an open element like <a href="foo">
   726		d.ungetc(b)
   727	
   728		var (
   729			name  Name
   730			empty bool
   731			attr  []Attr
   732		)
   733		if name, ok = d.nsname(); !ok {
   734			if d.err == nil {
   735				d.err = d.syntaxError("expected element name after <")
   736			}
   737			return nil, d.err
   738		}
   739	
   740		attr = []Attr{}
   741		for {
   742			d.space()
   743			if b, ok = d.mustgetc(); !ok {
   744				return nil, d.err
   745			}
   746			if b == '/' {
   747				empty = true
   748				if b, ok = d.mustgetc(); !ok {
   749					return nil, d.err
   750				}
   751				if b != '>' {
   752					d.err = d.syntaxError("expected /> in element")
   753					return nil, d.err
   754				}
   755				break
   756			}
   757			if b == '>' {
   758				break
   759			}
   760			d.ungetc(b)
   761	
   762			n := len(attr)
   763			if n >= cap(attr) {
   764				nCap := 2 * cap(attr)
   765				if nCap == 0 {
   766					nCap = 4
   767				}
   768				nattr := make([]Attr, n, nCap)
   769				copy(nattr, attr)
   770				attr = nattr
   771			}
   772			attr = attr[0 : n+1]
   773			a := &attr[n]
   774			if a.Name, ok = d.nsname(); !ok {
   775				if d.err == nil {
   776					d.err = d.syntaxError("expected attribute name in element")
   777				}
   778				return nil, d.err
   779			}
   780			d.space()
   781			if b, ok = d.mustgetc(); !ok {
   782				return nil, d.err
   783			}
   784			if b != '=' {
   785				if d.Strict {
   786					d.err = d.syntaxError("attribute name without = in element")
   787					return nil, d.err
   788				} else {
   789					d.ungetc(b)
   790					a.Value = a.Name.Local
   791				}
   792			} else {
   793				d.space()
   794				data := d.attrval()
   795				if data == nil {
   796					return nil, d.err
   797				}
   798				a.Value = string(data)
   799			}
   800		}
   801		if empty {
   802			d.needClose = true
   803			d.toClose = name
   804		}
   805		return StartElement{name, attr}, nil
   806	}
   807	
   808	func (d *Decoder) attrval() []byte {
   809		b, ok := d.mustgetc()
   810		if !ok {
   811			return nil
   812		}
   813		// Handle quoted attribute values
   814		if b == '"' || b == '\'' {
   815			return d.text(int(b), false)
   816		}
   817		// Handle unquoted attribute values for strict parsers
   818		if d.Strict {
   819			d.err = d.syntaxError("unquoted or missing attribute value in element")
   820			return nil
   821		}
   822		// Handle unquoted attribute values for unstrict parsers
   823		d.ungetc(b)
   824		d.buf.Reset()
   825		for {
   826			b, ok = d.mustgetc()
   827			if !ok {
   828				return nil
   829			}
   830			// http://www.w3.org/TR/REC-html40/intro/sgmltut.html#h-3.2.2
   831			if 'a' <= b && b <= 'z' || 'A' <= b && b <= 'Z' ||
   832				'0' <= b && b <= '9' || b == '_' || b == ':' || b == '-' {
   833				d.buf.WriteByte(b)
   834			} else {
   835				d.ungetc(b)
   836				break
   837			}
   838		}
   839		return d.buf.Bytes()
   840	}
   841	
   842	// Skip spaces if any
   843	func (d *Decoder) space() {
   844		for {
   845			b, ok := d.getc()
   846			if !ok {
   847				return
   848			}
   849			switch b {
   850			case ' ', '\r', '\n', '\t':
   851			default:
   852				d.ungetc(b)
   853				return
   854			}
   855		}
   856	}
   857	
   858	// Read a single byte.
   859	// If there is no byte to read, return ok==false
   860	// and leave the error in d.err.
   861	// Maintain line number.
   862	func (d *Decoder) getc() (b byte, ok bool) {
   863		if d.err != nil {
   864			return 0, false
   865		}
   866		if d.nextByte >= 0 {
   867			b = byte(d.nextByte)
   868			d.nextByte = -1
   869		} else {
   870			b, d.err = d.r.ReadByte()
   871			if d.err != nil {
   872				return 0, false
   873			}
   874			if d.saved != nil {
   875				d.saved.WriteByte(b)
   876			}
   877		}
   878		if b == '\n' {
   879			d.line++
   880		}
   881		d.offset++
   882		return b, true
   883	}
   884	
   885	// InputOffset returns the input stream byte offset of the current decoder position.
   886	// The offset gives the location of the end of the most recently returned token
   887	// and the beginning of the next token.
   888	func (d *Decoder) InputOffset() int64 {
   889		return d.offset
   890	}
   891	
   892	// Return saved offset.
   893	// If we did ungetc (nextByte >= 0), have to back up one.
   894	func (d *Decoder) savedOffset() int {
   895		n := d.saved.Len()
   896		if d.nextByte >= 0 {
   897			n--
   898		}
   899		return n
   900	}
   901	
   902	// Must read a single byte.
   903	// If there is no byte to read,
   904	// set d.err to SyntaxError("unexpected EOF")
   905	// and return ok==false
   906	func (d *Decoder) mustgetc() (b byte, ok bool) {
   907		if b, ok = d.getc(); !ok {
   908			if d.err == io.EOF {
   909				d.err = d.syntaxError("unexpected EOF")
   910			}
   911		}
   912		return
   913	}
   914	
   915	// Unread a single byte.
   916	func (d *Decoder) ungetc(b byte) {
   917		if b == '\n' {
   918			d.line--
   919		}
   920		d.nextByte = int(b)
   921		d.offset--
   922	}
   923	
   924	var entity = map[string]int{
   925		"lt":   '<',
   926		"gt":   '>',
   927		"amp":  '&',
   928		"apos": '\'',
   929		"quot": '"',
   930	}
   931	
   932	// Read plain text section (XML calls it character data).
   933	// If quote >= 0, we are in a quoted string and need to find the matching quote.
   934	// If cdata == true, we are in a <![CDATA[ section and need to find ]]>.
   935	// On failure return nil and leave the error in d.err.
   936	func (d *Decoder) text(quote int, cdata bool) []byte {
   937		var b0, b1 byte
   938		var trunc int
   939		d.buf.Reset()
   940	Input:
   941		for {
   942			b, ok := d.getc()
   943			if !ok {
   944				if cdata {
   945					if d.err == io.EOF {
   946						d.err = d.syntaxError("unexpected EOF in CDATA section")
   947					}
   948					return nil
   949				}
   950				break Input
   951			}
   952	
   953			// <![CDATA[ section ends with ]]>.
   954			// It is an error for ]]> to appear in ordinary text.
   955			if b0 == ']' && b1 == ']' && b == '>' {
   956				if cdata {
   957					trunc = 2
   958					break Input
   959				}
   960				d.err = d.syntaxError("unescaped ]]> not in CDATA section")
   961				return nil
   962			}
   963	
   964			// Stop reading text if we see a <.
   965			if b == '<' && !cdata {
   966				if quote >= 0 {
   967					d.err = d.syntaxError("unescaped < inside quoted string")
   968					return nil
   969				}
   970				d.ungetc('<')
   971				break Input
   972			}
   973			if quote >= 0 && b == byte(quote) {
   974				break Input
   975			}
   976			if b == '&' && !cdata {
   977				// Read escaped character expression up to semicolon.
   978				// XML in all its glory allows a document to define and use
   979				// its own character names with <!ENTITY ...> directives.
   980				// Parsers are required to recognize lt, gt, amp, apos, and quot
   981				// even if they have not been declared.
   982				before := d.buf.Len()
   983				d.buf.WriteByte('&')
   984				var ok bool
   985				var text string
   986				var haveText bool
   987				if b, ok = d.mustgetc(); !ok {
   988					return nil
   989				}
   990				if b == '#' {
   991					d.buf.WriteByte(b)
   992					if b, ok = d.mustgetc(); !ok {
   993						return nil
   994					}
   995					base := 10
   996					if b == 'x' {
   997						base = 16
   998						d.buf.WriteByte(b)
   999						if b, ok = d.mustgetc(); !ok {
  1000							return nil
  1001						}
  1002					}
  1003					start := d.buf.Len()
  1004					for '0' <= b && b <= '9' ||
  1005						base == 16 && 'a' <= b && b <= 'f' ||
  1006						base == 16 && 'A' <= b && b <= 'F' {
  1007						d.buf.WriteByte(b)
  1008						if b, ok = d.mustgetc(); !ok {
  1009							return nil
  1010						}
  1011					}
  1012					if b != ';' {
  1013						d.ungetc(b)
  1014					} else {
  1015						s := string(d.buf.Bytes()[start:])
  1016						d.buf.WriteByte(';')
  1017						n, err := strconv.ParseUint(s, base, 64)
  1018						if err == nil && n <= unicode.MaxRune {
  1019							text = string(n)
  1020							haveText = true
  1021						}
  1022					}
  1023				} else {
  1024					d.ungetc(b)
  1025					if !d.readName() {
  1026						if d.err != nil {
  1027							return nil
  1028						}
  1029						ok = false
  1030					}
  1031					if b, ok = d.mustgetc(); !ok {
  1032						return nil
  1033					}
  1034					if b != ';' {
  1035						d.ungetc(b)
  1036					} else {
  1037						name := d.buf.Bytes()[before+1:]
  1038						d.buf.WriteByte(';')
  1039						if isName(name) {
  1040							s := string(name)
  1041							if r, ok := entity[s]; ok {
  1042								text = string(r)
  1043								haveText = true
  1044							} else if d.Entity != nil {
  1045								text, haveText = d.Entity[s]
  1046							}
  1047						}
  1048					}
  1049				}
  1050	
  1051				if haveText {
  1052					d.buf.Truncate(before)
  1053					d.buf.Write([]byte(text))
  1054					b0, b1 = 0, 0
  1055					continue Input
  1056				}
  1057				if !d.Strict {
  1058					b0, b1 = 0, 0
  1059					continue Input
  1060				}
  1061				ent := string(d.buf.Bytes()[before:])
  1062				if ent[len(ent)-1] != ';' {
  1063					ent += " (no semicolon)"
  1064				}
  1065				d.err = d.syntaxError("invalid character entity " + ent)
  1066				return nil
  1067			}
  1068	
  1069			// We must rewrite unescaped \r and \r\n into \n.
  1070			if b == '\r' {
  1071				d.buf.WriteByte('\n')
  1072			} else if b1 == '\r' && b == '\n' {
  1073				// Skip \r\n--we already wrote \n.
  1074			} else {
  1075				d.buf.WriteByte(b)
  1076			}
  1077	
  1078			b0, b1 = b1, b
  1079		}
  1080		data := d.buf.Bytes()
  1081		data = data[0 : len(data)-trunc]
  1082	
  1083		// Inspect each rune for being a disallowed character.
  1084		buf := data
  1085		for len(buf) > 0 {
  1086			r, size := utf8.DecodeRune(buf)
  1087			if r == utf8.RuneError && size == 1 {
  1088				d.err = d.syntaxError("invalid UTF-8")
  1089				return nil
  1090			}
  1091			buf = buf[size:]
  1092			if !isInCharacterRange(r) {
  1093				d.err = d.syntaxError(fmt.Sprintf("illegal character code %U", r))
  1094				return nil
  1095			}
  1096		}
  1097	
  1098		return data
  1099	}
  1100	
  1101	// Decide whether the given rune is in the XML Character Range, per
  1102	// the Char production of http://www.xml.com/axml/testaxml.htm,
  1103	// Section 2.2 Characters.
  1104	func isInCharacterRange(r rune) (inrange bool) {
  1105		return r == 0x09 ||
  1106			r == 0x0A ||
  1107			r == 0x0D ||
  1108			r >= 0x20 && r <= 0xDF77 ||
  1109			r >= 0xE000 && r <= 0xFFFD ||
  1110			r >= 0x10000 && r <= 0x10FFFF
  1111	}
  1112	
  1113	// Get name space name: name with a : stuck in the middle.
  1114	// The part before the : is the name space identifier.
  1115	func (d *Decoder) nsname() (name Name, ok bool) {
  1116		s, ok := d.name()
  1117		if !ok {
  1118			return
  1119		}
  1120		i := strings.Index(s, ":")
  1121		if i < 0 {
  1122			name.Local = s
  1123		} else {
  1124			name.Space = s[0:i]
  1125			name.Local = s[i+1:]
  1126		}
  1127		return name, true
  1128	}
  1129	
  1130	// Get name: /first(first|second)*/
  1131	// Do not set d.err if the name is missing (unless unexpected EOF is received):
  1132	// let the caller provide better context.
  1133	func (d *Decoder) name() (s string, ok bool) {
  1134		d.buf.Reset()
  1135		if !d.readName() {
  1136			return "", false
  1137		}
  1138	
  1139		// Now we check the characters.
  1140		b := d.buf.Bytes()
  1141		if !isName(b) {
  1142			d.err = d.syntaxError("invalid XML name: " + string(b))
  1143			return "", false
  1144		}
  1145		return string(b), true
  1146	}
  1147	
  1148	// Read a name and append its bytes to d.buf.
  1149	// The name is delimited by any single-byte character not valid in names.
  1150	// All multi-byte characters are accepted; the caller must check their validity.
  1151	func (d *Decoder) readName() (ok bool) {
  1152		var b byte
  1153		if b, ok = d.mustgetc(); !ok {
  1154			return
  1155		}
  1156		if b < utf8.RuneSelf && !isNameByte(b) {
  1157			d.ungetc(b)
  1158			return false
  1159		}
  1160		d.buf.WriteByte(b)
  1161	
  1162		for {
  1163			if b, ok = d.mustgetc(); !ok {
  1164				return
  1165			}
  1166			if b < utf8.RuneSelf && !isNameByte(b) {
  1167				d.ungetc(b)
  1168				break
  1169			}
  1170			d.buf.WriteByte(b)
  1171		}
  1172		return true
  1173	}
  1174	
  1175	func isNameByte(c byte) bool {
  1176		return 'A' <= c && c <= 'Z' ||
  1177			'a' <= c && c <= 'z' ||
  1178			'0' <= c && c <= '9' ||
  1179			c == '_' || c == ':' || c == '.' || c == '-'
  1180	}
  1181	
  1182	func isName(s []byte) bool {
  1183		if len(s) == 0 {
  1184			return false
  1185		}
  1186		c, n := utf8.DecodeRune(s)
  1187		if c == utf8.RuneError && n == 1 {
  1188			return false
  1189		}
  1190		if !unicode.Is(first, c) {
  1191			return false
  1192		}
  1193		for n < len(s) {
  1194			s = s[n:]
  1195			c, n = utf8.DecodeRune(s)
  1196			if c == utf8.RuneError && n == 1 {
  1197				return false
  1198			}
  1199			if !unicode.Is(first, c) && !unicode.Is(second, c) {
  1200				return false
  1201			}
  1202		}
  1203		return true
  1204	}
  1205	
  1206	func isNameString(s string) bool {
  1207		if len(s) == 0 {
  1208			return false
  1209		}
  1210		c, n := utf8.DecodeRuneInString(s)
  1211		if c == utf8.RuneError && n == 1 {
  1212			return false
  1213		}
  1214		if !unicode.Is(first, c) {
  1215			return false
  1216		}
  1217		for n < len(s) {
  1218			s = s[n:]
  1219			c, n = utf8.DecodeRuneInString(s)
  1220			if c == utf8.RuneError && n == 1 {
  1221				return false
  1222			}
  1223			if !unicode.Is(first, c) && !unicode.Is(second, c) {
  1224				return false
  1225			}
  1226		}
  1227		return true
  1228	}
  1229	
  1230	// These tables were generated by cut and paste from Appendix B of
  1231	// the XML spec at http://www.xml.com/axml/testaxml.htm
  1232	// and then reformatting.  First corresponds to (Letter | '_' | ':')
  1233	// and second corresponds to NameChar.
  1234	
  1235	var first = &unicode.RangeTable{
  1236		R16: []unicode.Range16{
  1237			{0x003A, 0x003A, 1},
  1238			{0x0041, 0x005A, 1},
  1239			{0x005F, 0x005F, 1},
  1240			{0x0061, 0x007A, 1},
  1241			{0x00C0, 0x00D6, 1},
  1242			{0x00D8, 0x00F6, 1},
  1243			{0x00F8, 0x00FF, 1},
  1244			{0x0100, 0x0131, 1},
  1245			{0x0134, 0x013E, 1},
  1246			{0x0141, 0x0148, 1},
  1247			{0x014A, 0x017E, 1},
  1248			{0x0180, 0x01C3, 1},
  1249			{0x01CD, 0x01F0, 1},
  1250			{0x01F4, 0x01F5, 1},
  1251			{0x01FA, 0x0217, 1},
  1252			{0x0250, 0x02A8, 1},
  1253			{0x02BB, 0x02C1, 1},
  1254			{0x0386, 0x0386, 1},
  1255			{0x0388, 0x038A, 1},
  1256			{0x038C, 0x038C, 1},
  1257			{0x038E, 0x03A1, 1},
  1258			{0x03A3, 0x03CE, 1},
  1259			{0x03D0, 0x03D6, 1},
  1260			{0x03DA, 0x03E0, 2},
  1261			{0x03E2, 0x03F3, 1},
  1262			{0x0401, 0x040C, 1},
  1263			{0x040E, 0x044F, 1},
  1264			{0x0451, 0x045C, 1},
  1265			{0x045E, 0x0481, 1},
  1266			{0x0490, 0x04C4, 1},
  1267			{0x04C7, 0x04C8, 1},
  1268			{0x04CB, 0x04CC, 1},
  1269			{0x04D0, 0x04EB, 1},
  1270			{0x04EE, 0x04F5, 1},
  1271			{0x04F8, 0x04F9, 1},
  1272			{0x0531, 0x0556, 1},
  1273			{0x0559, 0x0559, 1},
  1274			{0x0561, 0x0586, 1},
  1275			{0x05D0, 0x05EA, 1},
  1276			{0x05F0, 0x05F2, 1},
  1277			{0x0621, 0x063A, 1},
  1278			{0x0641, 0x064A, 1},
  1279			{0x0671, 0x06B7, 1},
  1280			{0x06BA, 0x06BE, 1},
  1281			{0x06C0, 0x06CE, 1},
  1282			{0x06D0, 0x06D3, 1},
  1283			{0x06D5, 0x06D5, 1},
  1284			{0x06E5, 0x06E6, 1},
  1285			{0x0905, 0x0939, 1},
  1286			{0x093D, 0x093D, 1},
  1287			{0x0958, 0x0961, 1},
  1288			{0x0985, 0x098C, 1},
  1289			{0x098F, 0x0990, 1},
  1290			{0x0993, 0x09A8, 1},
  1291			{0x09AA, 0x09B0, 1},
  1292			{0x09B2, 0x09B2, 1},
  1293			{0x09B6, 0x09B9, 1},
  1294			{0x09DC, 0x09DD, 1},
  1295			{0x09DF, 0x09E1, 1},
  1296			{0x09F0, 0x09F1, 1},
  1297			{0x0A05, 0x0A0A, 1},
  1298			{0x0A0F, 0x0A10, 1},
  1299			{0x0A13, 0x0A28, 1},
  1300			{0x0A2A, 0x0A30, 1},
  1301			{0x0A32, 0x0A33, 1},
  1302			{0x0A35, 0x0A36, 1},
  1303			{0x0A38, 0x0A39, 1},
  1304			{0x0A59, 0x0A5C, 1},
  1305			{0x0A5E, 0x0A5E, 1},
  1306			{0x0A72, 0x0A74, 1},
  1307			{0x0A85, 0x0A8B, 1},
  1308			{0x0A8D, 0x0A8D, 1},
  1309			{0x0A8F, 0x0A91, 1},
  1310			{0x0A93, 0x0AA8, 1},
  1311			{0x0AAA, 0x0AB0, 1},
  1312			{0x0AB2, 0x0AB3, 1},
  1313			{0x0AB5, 0x0AB9, 1},
  1314			{0x0ABD, 0x0AE0, 0x23},
  1315			{0x0B05, 0x0B0C, 1},
  1316			{0x0B0F, 0x0B10, 1},
  1317			{0x0B13, 0x0B28, 1},
  1318			{0x0B2A, 0x0B30, 1},
  1319			{0x0B32, 0x0B33, 1},
  1320			{0x0B36, 0x0B39, 1},
  1321			{0x0B3D, 0x0B3D, 1},
  1322			{0x0B5C, 0x0B5D, 1},
  1323			{0x0B5F, 0x0B61, 1},
  1324			{0x0B85, 0x0B8A, 1},
  1325			{0x0B8E, 0x0B90, 1},
  1326			{0x0B92, 0x0B95, 1},
  1327			{0x0B99, 0x0B9A, 1},
  1328			{0x0B9C, 0x0B9C, 1},
  1329			{0x0B9E, 0x0B9F, 1},
  1330			{0x0BA3, 0x0BA4, 1},
  1331			{0x0BA8, 0x0BAA, 1},
  1332			{0x0BAE, 0x0BB5, 1},
  1333			{0x0BB7, 0x0BB9, 1},
  1334			{0x0C05, 0x0C0C, 1},
  1335			{0x0C0E, 0x0C10, 1},
  1336			{0x0C12, 0x0C28, 1},
  1337			{0x0C2A, 0x0C33, 1},
  1338			{0x0C35, 0x0C39, 1},
  1339			{0x0C60, 0x0C61, 1},
  1340			{0x0C85, 0x0C8C, 1},
  1341			{0x0C8E, 0x0C90, 1},
  1342			{0x0C92, 0x0CA8, 1},
  1343			{0x0CAA, 0x0CB3, 1},
  1344			{0x0CB5, 0x0CB9, 1},
  1345			{0x0CDE, 0x0CDE, 1},
  1346			{0x0CE0, 0x0CE1, 1},
  1347			{0x0D05, 0x0D0C, 1},
  1348			{0x0D0E, 0x0D10, 1},
  1349			{0x0D12, 0x0D28, 1},
  1350			{0x0D2A, 0x0D39, 1},
  1351			{0x0D60, 0x0D61, 1},
  1352			{0x0E01, 0x0E2E, 1},
  1353			{0x0E30, 0x0E30, 1},
  1354			{0x0E32, 0x0E33, 1},
  1355			{0x0E40, 0x0E45, 1},
  1356			{0x0E81, 0x0E82, 1},
  1357			{0x0E84, 0x0E84, 1},
  1358			{0x0E87, 0x0E88, 1},
  1359			{0x0E8A, 0x0E8D, 3},
  1360			{0x0E94, 0x0E97, 1},
  1361			{0x0E99, 0x0E9F, 1},
  1362			{0x0EA1, 0x0EA3, 1},
  1363			{0x0EA5, 0x0EA7, 2},
  1364			{0x0EAA, 0x0EAB, 1},
  1365			{0x0EAD, 0x0EAE, 1},
  1366			{0x0EB0, 0x0EB0, 1},
  1367			{0x0EB2, 0x0EB3, 1},
  1368			{0x0EBD, 0x0EBD, 1},
  1369			{0x0EC0, 0x0EC4, 1},
  1370			{0x0F40, 0x0F47, 1},
  1371			{0x0F49, 0x0F69, 1},
  1372			{0x10A0, 0x10C5, 1},
  1373			{0x10D0, 0x10F6, 1},
  1374			{0x1100, 0x1100, 1},
  1375			{0x1102, 0x1103, 1},
  1376			{0x1105, 0x1107, 1},
  1377			{0x1109, 0x1109, 1},
  1378			{0x110B, 0x110C, 1},
  1379			{0x110E, 0x1112, 1},
  1380			{0x113C, 0x1140, 2},
  1381			{0x114C, 0x1150, 2},
  1382			{0x1154, 0x1155, 1},
  1383			{0x1159, 0x1159, 1},
  1384			{0x115F, 0x1161, 1},
  1385			{0x1163, 0x1169, 2},
  1386			{0x116D, 0x116E, 1},
  1387			{0x1172, 0x1173, 1},
  1388			{0x1175, 0x119E, 0x119E - 0x1175},
  1389			{0x11A8, 0x11AB, 0x11AB - 0x11A8},
  1390			{0x11AE, 0x11AF, 1},
  1391			{0x11B7, 0x11B8, 1},
  1392			{0x11BA, 0x11BA, 1},
  1393			{0x11BC, 0x11C2, 1},
  1394			{0x11EB, 0x11F0, 0x11F0 - 0x11EB},
  1395			{0x11F9, 0x11F9, 1},
  1396			{0x1E00, 0x1E9B, 1},
  1397			{0x1EA0, 0x1EF9, 1},
  1398			{0x1F00, 0x1F15, 1},
  1399			{0x1F18, 0x1F1D, 1},
  1400			{0x1F20, 0x1F45, 1},
  1401			{0x1F48, 0x1F4D, 1},
  1402			{0x1F50, 0x1F57, 1},
  1403			{0x1F59, 0x1F5B, 0x1F5B - 0x1F59},
  1404			{0x1F5D, 0x1F5D, 1},
  1405			{0x1F5F, 0x1F7D, 1},
  1406			{0x1F80, 0x1FB4, 1},
  1407			{0x1FB6, 0x1FBC, 1},
  1408			{0x1FBE, 0x1FBE, 1},
  1409			{0x1FC2, 0x1FC4, 1},
  1410			{0x1FC6, 0x1FCC, 1},
  1411			{0x1FD0, 0x1FD3, 1},
  1412			{0x1FD6, 0x1FDB, 1},
  1413			{0x1FE0, 0x1FEC, 1},
  1414			{0x1FF2, 0x1FF4, 1},
  1415			{0x1FF6, 0x1FFC, 1},
  1416			{0x2126, 0x2126, 1},
  1417			{0x212A, 0x212B, 1},
  1418			{0x212E, 0x212E, 1},
  1419			{0x2180, 0x2182, 1},
  1420			{0x3007, 0x3007, 1},
  1421			{0x3021, 0x3029, 1},
  1422			{0x3041, 0x3094, 1},
  1423			{0x30A1, 0x30FA, 1},
  1424			{0x3105, 0x312C, 1},
  1425			{0x4E00, 0x9FA5, 1},
  1426			{0xAC00, 0xD7A3, 1},
  1427		},
  1428	}
  1429	
  1430	var second = &unicode.RangeTable{
  1431		R16: []unicode.Range16{
  1432			{0x002D, 0x002E, 1},
  1433			{0x0030, 0x0039, 1},
  1434			{0x00B7, 0x00B7, 1},
  1435			{0x02D0, 0x02D1, 1},
  1436			{0x0300, 0x0345, 1},
  1437			{0x0360, 0x0361, 1},
  1438			{0x0387, 0x0387, 1},
  1439			{0x0483, 0x0486, 1},
  1440			{0x0591, 0x05A1, 1},
  1441			{0x05A3, 0x05B9, 1},
  1442			{0x05BB, 0x05BD, 1},
  1443			{0x05BF, 0x05BF, 1},
  1444			{0x05C1, 0x05C2, 1},
  1445			{0x05C4, 0x0640, 0x0640 - 0x05C4},
  1446			{0x064B, 0x0652, 1},
  1447			{0x0660, 0x0669, 1},
  1448			{0x0670, 0x0670, 1},
  1449			{0x06D6, 0x06DC, 1},
  1450			{0x06DD, 0x06DF, 1},
  1451			{0x06E0, 0x06E4, 1},
  1452			{0x06E7, 0x06E8, 1},
  1453			{0x06EA, 0x06ED, 1},
  1454			{0x06F0, 0x06F9, 1},
  1455			{0x0901, 0x0903, 1},
  1456			{0x093C, 0x093C, 1},
  1457			{0x093E, 0x094C, 1},
  1458			{0x094D, 0x094D, 1},
  1459			{0x0951, 0x0954, 1},
  1460			{0x0962, 0x0963, 1},
  1461			{0x0966, 0x096F, 1},
  1462			{0x0981, 0x0983, 1},
  1463			{0x09BC, 0x09BC, 1},
  1464			{0x09BE, 0x09BF, 1},
  1465			{0x09C0, 0x09C4, 1},
  1466			{0x09C7, 0x09C8, 1},
  1467			{0x09CB, 0x09CD, 1},
  1468			{0x09D7, 0x09D7, 1},
  1469			{0x09E2, 0x09E3, 1},
  1470			{0x09E6, 0x09EF, 1},
  1471			{0x0A02, 0x0A3C, 0x3A},
  1472			{0x0A3E, 0x0A3F, 1},
  1473			{0x0A40, 0x0A42, 1},
  1474			{0x0A47, 0x0A48, 1},
  1475			{0x0A4B, 0x0A4D, 1},
  1476			{0x0A66, 0x0A6F, 1},
  1477			{0x0A70, 0x0A71, 1},
  1478			{0x0A81, 0x0A83, 1},
  1479			{0x0ABC, 0x0ABC, 1},
  1480			{0x0ABE, 0x0AC5, 1},
  1481			{0x0AC7, 0x0AC9, 1},
  1482			{0x0ACB, 0x0ACD, 1},
  1483			{0x0AE6, 0x0AEF, 1},
  1484			{0x0B01, 0x0B03, 1},
  1485			{0x0B3C, 0x0B3C, 1},
  1486			{0x0B3E, 0x0B43, 1},
  1487			{0x0B47, 0x0B48, 1},
  1488			{0x0B4B, 0x0B4D, 1},
  1489			{0x0B56, 0x0B57, 1},
  1490			{0x0B66, 0x0B6F, 1},
  1491			{0x0B82, 0x0B83, 1},
  1492			{0x0BBE, 0x0BC2, 1},
  1493			{0x0BC6, 0x0BC8, 1},
  1494			{0x0BCA, 0x0BCD, 1},
  1495			{0x0BD7, 0x0BD7, 1},
  1496			{0x0BE7, 0x0BEF, 1},
  1497			{0x0C01, 0x0C03, 1},
  1498			{0x0C3E, 0x0C44, 1},
  1499			{0x0C46, 0x0C48, 1},
  1500			{0x0C4A, 0x0C4D, 1},
  1501			{0x0C55, 0x0C56, 1},
  1502			{0x0C66, 0x0C6F, 1},
  1503			{0x0C82, 0x0C83, 1},
  1504			{0x0CBE, 0x0CC4, 1},
  1505			{0x0CC6, 0x0CC8, 1},
  1506			{0x0CCA, 0x0CCD, 1},
  1507			{0x0CD5, 0x0CD6, 1},
  1508			{0x0CE6, 0x0CEF, 1},
  1509			{0x0D02, 0x0D03, 1},
  1510			{0x0D3E, 0x0D43, 1},
  1511			{0x0D46, 0x0D48, 1},
  1512			{0x0D4A, 0x0D4D, 1},
  1513			{0x0D57, 0x0D57, 1},
  1514			{0x0D66, 0x0D6F, 1},
  1515			{0x0E31, 0x0E31, 1},
  1516			{0x0E34, 0x0E3A, 1},
  1517			{0x0E46, 0x0E46, 1},
  1518			{0x0E47, 0x0E4E, 1},
  1519			{0x0E50, 0x0E59, 1},
  1520			{0x0EB1, 0x0EB1, 1},
  1521			{0x0EB4, 0x0EB9, 1},
  1522			{0x0EBB, 0x0EBC, 1},
  1523			{0x0EC6, 0x0EC6, 1},
  1524			{0x0EC8, 0x0ECD, 1},
  1525			{0x0ED0, 0x0ED9, 1},
  1526			{0x0F18, 0x0F19, 1},
  1527			{0x0F20, 0x0F29, 1},
  1528			{0x0F35, 0x0F39, 2},
  1529			{0x0F3E, 0x0F3F, 1},
  1530			{0x0F71, 0x0F84, 1},
  1531			{0x0F86, 0x0F8B, 1},
  1532			{0x0F90, 0x0F95, 1},
  1533			{0x0F97, 0x0F97, 1},
  1534			{0x0F99, 0x0FAD, 1},
  1535			{0x0FB1, 0x0FB7, 1},
  1536			{0x0FB9, 0x0FB9, 1},
  1537			{0x20D0, 0x20DC, 1},
  1538			{0x20E1, 0x3005, 0x3005 - 0x20E1},
  1539			{0x302A, 0x302F, 1},
  1540			{0x3031, 0x3035, 1},
  1541			{0x3099, 0x309A, 1},
  1542			{0x309D, 0x309E, 1},
  1543			{0x30FC, 0x30FE, 1},
  1544		},
  1545	}
  1546	
  1547	// HTMLEntity is an entity map containing translations for the
  1548	// standard HTML entity characters.
  1549	var HTMLEntity = htmlEntity
  1550	
  1551	var htmlEntity = map[string]string{
  1552		/*
  1553			hget http://www.w3.org/TR/html4/sgml/entities.html |
  1554			ssam '
  1555				,y /\&gt;/ x/\&lt;(.|\n)+/ s/\n/ /g
  1556				,x v/^\&lt;!ENTITY/d
  1557				,s/\&lt;!ENTITY ([^ ]+) .*U\+([0-9A-F][0-9A-F][0-9A-F][0-9A-F]) .+/	"\1": "\\u\2",/g
  1558			'
  1559		*/
  1560		"nbsp":     "\u00A0",
  1561		"iexcl":    "\u00A1",
  1562		"cent":     "\u00A2",
  1563		"pound":    "\u00A3",
  1564		"curren":   "\u00A4",
  1565		"yen":      "\u00A5",
  1566		"brvbar":   "\u00A6",
  1567		"sect":     "\u00A7",
  1568		"uml":      "\u00A8",
  1569		"copy":     "\u00A9",
  1570		"ordf":     "\u00AA",
  1571		"laquo":    "\u00AB",
  1572		"not":      "\u00AC",
  1573		"shy":      "\u00AD",
  1574		"reg":      "\u00AE",
  1575		"macr":     "\u00AF",
  1576		"deg":      "\u00B0",
  1577		"plusmn":   "\u00B1",
  1578		"sup2":     "\u00B2",
  1579		"sup3":     "\u00B3",
  1580		"acute":    "\u00B4",
  1581		"micro":    "\u00B5",
  1582		"para":     "\u00B6",
  1583		"middot":   "\u00B7",
  1584		"cedil":    "\u00B8",
  1585		"sup1":     "\u00B9",
  1586		"ordm":     "\u00BA",
  1587		"raquo":    "\u00BB",
  1588		"frac14":   "\u00BC",
  1589		"frac12":   "\u00BD",
  1590		"frac34":   "\u00BE",
  1591		"iquest":   "\u00BF",
  1592		"Agrave":   "\u00C0",
  1593		"Aacute":   "\u00C1",
  1594		"Acirc":    "\u00C2",
  1595		"Atilde":   "\u00C3",
  1596		"Auml":     "\u00C4",
  1597		"Aring":    "\u00C5",
  1598		"AElig":    "\u00C6",
  1599		"Ccedil":   "\u00C7",
  1600		"Egrave":   "\u00C8",
  1601		"Eacute":   "\u00C9",
  1602		"Ecirc":    "\u00CA",
  1603		"Euml":     "\u00CB",
  1604		"Igrave":   "\u00CC",
  1605		"Iacute":   "\u00CD",
  1606		"Icirc":    "\u00CE",
  1607		"Iuml":     "\u00CF",
  1608		"ETH":      "\u00D0",
  1609		"Ntilde":   "\u00D1",
  1610		"Ograve":   "\u00D2",
  1611		"Oacute":   "\u00D3",
  1612		"Ocirc":    "\u00D4",
  1613		"Otilde":   "\u00D5",
  1614		"Ouml":     "\u00D6",
  1615		"times":    "\u00D7",
  1616		"Oslash":   "\u00D8",
  1617		"Ugrave":   "\u00D9",
  1618		"Uacute":   "\u00DA",
  1619		"Ucirc":    "\u00DB",
  1620		"Uuml":     "\u00DC",
  1621		"Yacute":   "\u00DD",
  1622		"THORN":    "\u00DE",
  1623		"szlig":    "\u00DF",
  1624		"agrave":   "\u00E0",
  1625		"aacute":   "\u00E1",
  1626		"acirc":    "\u00E2",
  1627		"atilde":   "\u00E3",
  1628		"auml":     "\u00E4",
  1629		"aring":    "\u00E5",
  1630		"aelig":    "\u00E6",
  1631		"ccedil":   "\u00E7",
  1632		"egrave":   "\u00E8",
  1633		"eacute":   "\u00E9",
  1634		"ecirc":    "\u00EA",
  1635		"euml":     "\u00EB",
  1636		"igrave":   "\u00EC",
  1637		"iacute":   "\u00ED",
  1638		"icirc":    "\u00EE",
  1639		"iuml":     "\u00EF",
  1640		"eth":      "\u00F0",
  1641		"ntilde":   "\u00F1",
  1642		"ograve":   "\u00F2",
  1643		"oacute":   "\u00F3",
  1644		"ocirc":    "\u00F4",
  1645		"otilde":   "\u00F5",
  1646		"ouml":     "\u00F6",
  1647		"divide":   "\u00F7",
  1648		"oslash":   "\u00F8",
  1649		"ugrave":   "\u00F9",
  1650		"uacute":   "\u00FA",
  1651		"ucirc":    "\u00FB",
  1652		"uuml":     "\u00FC",
  1653		"yacute":   "\u00FD",
  1654		"thorn":    "\u00FE",
  1655		"yuml":     "\u00FF",
  1656		"fnof":     "\u0192",
  1657		"Alpha":    "\u0391",
  1658		"Beta":     "\u0392",
  1659		"Gamma":    "\u0393",
  1660		"Delta":    "\u0394",
  1661		"Epsilon":  "\u0395",
  1662		"Zeta":     "\u0396",
  1663		"Eta":      "\u0397",
  1664		"Theta":    "\u0398",
  1665		"Iota":     "\u0399",
  1666		"Kappa":    "\u039A",
  1667		"Lambda":   "\u039B",
  1668		"Mu":       "\u039C",
  1669		"Nu":       "\u039D",
  1670		"Xi":       "\u039E",
  1671		"Omicron":  "\u039F",
  1672		"Pi":       "\u03A0",
  1673		"Rho":      "\u03A1",
  1674		"Sigma":    "\u03A3",
  1675		"Tau":      "\u03A4",
  1676		"Upsilon":  "\u03A5",
  1677		"Phi":      "\u03A6",
  1678		"Chi":      "\u03A7",
  1679		"Psi":      "\u03A8",
  1680		"Omega":    "\u03A9",
  1681		"alpha":    "\u03B1",
  1682		"beta":     "\u03B2",
  1683		"gamma":    "\u03B3",
  1684		"delta":    "\u03B4",
  1685		"epsilon":  "\u03B5",
  1686		"zeta":     "\u03B6",
  1687		"eta":      "\u03B7",
  1688		"theta":    "\u03B8",
  1689		"iota":     "\u03B9",
  1690		"kappa":    "\u03BA",
  1691		"lambda":   "\u03BB",
  1692		"mu":       "\u03BC",
  1693		"nu":       "\u03BD",
  1694		"xi":       "\u03BE",
  1695		"omicron":  "\u03BF",
  1696		"pi":       "\u03C0",
  1697		"rho":      "\u03C1",
  1698		"sigmaf":   "\u03C2",
  1699		"sigma":    "\u03C3",
  1700		"tau":      "\u03C4",
  1701		"upsilon":  "\u03C5",
  1702		"phi":      "\u03C6",
  1703		"chi":      "\u03C7",
  1704		"psi":      "\u03C8",
  1705		"omega":    "\u03C9",
  1706		"thetasym": "\u03D1",
  1707		"upsih":    "\u03D2",
  1708		"piv":      "\u03D6",
  1709		"bull":     "\u2022",
  1710		"hellip":   "\u2026",
  1711		"prime":    "\u2032",
  1712		"Prime":    "\u2033",
  1713		"oline":    "\u203E",
  1714		"frasl":    "\u2044",
  1715		"weierp":   "\u2118",
  1716		"image":    "\u2111",
  1717		"real":     "\u211C",
  1718		"trade":    "\u2122",
  1719		"alefsym":  "\u2135",
  1720		"larr":     "\u2190",
  1721		"uarr":     "\u2191",
  1722		"rarr":     "\u2192",
  1723		"darr":     "\u2193",
  1724		"harr":     "\u2194",
  1725		"crarr":    "\u21B5",
  1726		"lArr":     "\u21D0",
  1727		"uArr":     "\u21D1",
  1728		"rArr":     "\u21D2",
  1729		"dArr":     "\u21D3",
  1730		"hArr":     "\u21D4",
  1731		"forall":   "\u2200",
  1732		"part":     "\u2202",
  1733		"exist":    "\u2203",
  1734		"empty":    "\u2205",
  1735		"nabla":    "\u2207",
  1736		"isin":     "\u2208",
  1737		"notin":    "\u2209",
  1738		"ni":       "\u220B",
  1739		"prod":     "\u220F",
  1740		"sum":      "\u2211",
  1741		"minus":    "\u2212",
  1742		"lowast":   "\u2217",
  1743		"radic":    "\u221A",
  1744		"prop":     "\u221D",
  1745		"infin":    "\u221E",
  1746		"ang":      "\u2220",
  1747		"and":      "\u2227",
  1748		"or":       "\u2228",
  1749		"cap":      "\u2229",
  1750		"cup":      "\u222A",
  1751		"int":      "\u222B",
  1752		"there4":   "\u2234",
  1753		"sim":      "\u223C",
  1754		"cong":     "\u2245",
  1755		"asymp":    "\u2248",
  1756		"ne":       "\u2260",
  1757		"equiv":    "\u2261",
  1758		"le":       "\u2264",
  1759		"ge":       "\u2265",
  1760		"sub":      "\u2282",
  1761		"sup":      "\u2283",
  1762		"nsub":     "\u2284",
  1763		"sube":     "\u2286",
  1764		"supe":     "\u2287",
  1765		"oplus":    "\u2295",
  1766		"otimes":   "\u2297",
  1767		"perp":     "\u22A5",
  1768		"sdot":     "\u22C5",
  1769		"lceil":    "\u2308",
  1770		"rceil":    "\u2309",
  1771		"lfloor":   "\u230A",
  1772		"rfloor":   "\u230B",
  1773		"lang":     "\u2329",
  1774		"rang":     "\u232A",
  1775		"loz":      "\u25CA",
  1776		"spades":   "\u2660",
  1777		"clubs":    "\u2663",
  1778		"hearts":   "\u2665",
  1779		"diams":    "\u2666",
  1780		"quot":     "\u0022",
  1781		"amp":      "\u0026",
  1782		"lt":       "\u003C",
  1783		"gt":       "\u003E",
  1784		"OElig":    "\u0152",
  1785		"oelig":    "\u0153",
  1786		"Scaron":   "\u0160",
  1787		"scaron":   "\u0161",
  1788		"Yuml":     "\u0178",
  1789		"circ":     "\u02C6",
  1790		"tilde":    "\u02DC",
  1791		"ensp":     "\u2002",
  1792		"emsp":     "\u2003",
  1793		"thinsp":   "\u2009",
  1794		"zwnj":     "\u200C",
  1795		"zwj":      "\u200D",
  1796		"lrm":      "\u200E",
  1797		"rlm":      "\u200F",
  1798		"ndash":    "\u2013",
  1799		"mdash":    "\u2014",
  1800		"lsquo":    "\u2018",
  1801		"rsquo":    "\u2019",
  1802		"sbquo":    "\u201A",
  1803		"ldquo":    "\u201C",
  1804		"rdquo":    "\u201D",
  1805		"bdquo":    "\u201E",
  1806		"dagger":   "\u2020",
  1807		"Dagger":   "\u2021",
  1808		"permil":   "\u2030",
  1809		"lsaquo":   "\u2039",
  1810		"rsaquo":   "\u203A",
  1811		"euro":     "\u20AC",
  1812	}
  1813	
  1814	// HTMLAutoClose is the set of HTML elements that
  1815	// should be considered to close automatically.
  1816	var HTMLAutoClose = htmlAutoClose
  1817	
  1818	var htmlAutoClose = []string{
  1819		/*
  1820			hget http://www.w3.org/TR/html4/loose.dtd |
  1821			9 sed -n 's/<!ELEMENT ([^ ]*) +- O EMPTY.+/	"\1",/p' | tr A-Z a-z
  1822		*/
  1823		"basefont",
  1824		"br",
  1825		"area",
  1826		"link",
  1827		"img",
  1828		"param",
  1829		"hr",
  1830		"input",
  1831		"col",
  1832		"frame",
  1833		"isindex",
  1834		"base",
  1835		"meta",
  1836	}
  1837	
  1838	var (
  1839		esc_quot = []byte("&#34;") // shorter than "&quot;"
  1840		esc_apos = []byte("&#39;") // shorter than "&apos;"
  1841		esc_amp  = []byte("&amp;")
  1842		esc_lt   = []byte("&lt;")
  1843		esc_gt   = []byte("&gt;")
  1844		esc_tab  = []byte("&#x9;")
  1845		esc_nl   = []byte("&#xA;")
  1846		esc_cr   = []byte("&#xD;")
  1847		esc_fffd = []byte("\uFFFD") // Unicode replacement character
  1848	)
  1849	
  1850	// EscapeText writes to w the properly escaped XML equivalent
  1851	// of the plain text data s.
  1852	func EscapeText(w io.Writer, s []byte) error {
  1853		return escapeText(w, s, true)
  1854	}
  1855	
  1856	// escapeText writes to w the properly escaped XML equivalent
  1857	// of the plain text data s. If escapeNewline is true, newline
  1858	// characters will be escaped.
  1859	func escapeText(w io.Writer, s []byte, escapeNewline bool) error {
  1860		var esc []byte
  1861		last := 0
  1862		for i := 0; i < len(s); {
  1863			r, width := utf8.DecodeRune(s[i:])
  1864			i += width
  1865			switch r {
  1866			case '"':
  1867				esc = esc_quot
  1868			case '\'':
  1869				esc = esc_apos
  1870			case '&':
  1871				esc = esc_amp
  1872			case '<':
  1873				esc = esc_lt
  1874			case '>':
  1875				esc = esc_gt
  1876			case '\t':
  1877				esc = esc_tab
  1878			case '\n':
  1879				if !escapeNewline {
  1880					continue
  1881				}
  1882				esc = esc_nl
  1883			case '\r':
  1884				esc = esc_cr
  1885			default:
  1886				if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) {
  1887					esc = esc_fffd
  1888					break
  1889				}
  1890				continue
  1891			}
  1892			if _, err := w.Write(s[last : i-width]); err != nil {
  1893				return err
  1894			}
  1895			if _, err := w.Write(esc); err != nil {
  1896				return err
  1897			}
  1898			last = i
  1899		}
  1900		if _, err := w.Write(s[last:]); err != nil {
  1901			return err
  1902		}
  1903		return nil
  1904	}
  1905	
  1906	// EscapeString writes to p the properly escaped XML equivalent
  1907	// of the plain text data s.
  1908	func (p *printer) EscapeString(s string) {
  1909		var esc []byte
  1910		last := 0
  1911		for i := 0; i < len(s); {
  1912			r, width := utf8.DecodeRuneInString(s[i:])
  1913			i += width
  1914			switch r {
  1915			case '"':
  1916				esc = esc_quot
  1917			case '\'':
  1918				esc = esc_apos
  1919			case '&':
  1920				esc = esc_amp
  1921			case '<':
  1922				esc = esc_lt
  1923			case '>':
  1924				esc = esc_gt
  1925			case '\t':
  1926				esc = esc_tab
  1927			case '\n':
  1928				esc = esc_nl
  1929			case '\r':
  1930				esc = esc_cr
  1931			default:
  1932				if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) {
  1933					esc = esc_fffd
  1934					break
  1935				}
  1936				continue
  1937			}
  1938			p.WriteString(s[last : i-width])
  1939			p.Write(esc)
  1940			last = i
  1941		}
  1942		p.WriteString(s[last:])
  1943	}
  1944	
  1945	// Escape is like EscapeText but omits the error return value.
  1946	// It is provided for backwards compatibility with Go 1.0.
  1947	// Code targeting Go 1.1 or later should use EscapeText.
  1948	func Escape(w io.Writer, s []byte) {
  1949		EscapeText(w, s)
  1950	}
  1951	
  1952	var (
  1953		cdataStart  = []byte("<![CDATA[")
  1954		cdataEnd    = []byte("]]>")
  1955		cdataEscape = []byte("]]]]><![CDATA[>")
  1956	)
  1957	
  1958	// emitCDATA writes to w the CDATA-wrapped plain text data s.
  1959	// It escapes CDATA directives nested in s.
  1960	func emitCDATA(w io.Writer, s []byte) error {
  1961		if len(s) == 0 {
  1962			return nil
  1963		}
  1964		if _, err := w.Write(cdataStart); err != nil {
  1965			return err
  1966		}
  1967		for {
  1968			i := bytes.Index(s, cdataEnd)
  1969			if i >= 0 && i+len(cdataEnd) <= len(s) {
  1970				// Found a nested CDATA directive end.
  1971				if _, err := w.Write(s[:i]); err != nil {
  1972					return err
  1973				}
  1974				if _, err := w.Write(cdataEscape); err != nil {
  1975					return err
  1976				}
  1977				i += len(cdataEnd)
  1978			} else {
  1979				if _, err := w.Write(s); err != nil {
  1980					return err
  1981				}
  1982				break
  1983			}
  1984			s = s[i:]
  1985		}
  1986		if _, err := w.Write(cdataEnd); err != nil {
  1987			return err
  1988		}
  1989		return nil
  1990	}
  1991	
  1992	// procInst parses the `param="..."` or `param='...'`
  1993	// value out of the provided string, returning "" if not found.
  1994	func procInst(param, s string) string {
  1995		// TODO: this parsing is somewhat lame and not exact.
  1996		// It works for all actual cases, though.
  1997		param = param + "="
  1998		idx := strings.Index(s, param)
  1999		if idx == -1 {
  2000			return ""
  2001		}
  2002		v := s[idx+len(param):]
  2003		if v == "" {
  2004			return ""
  2005		}
  2006		if v[0] != '\'' && v[0] != '"' {
  2007			return ""
  2008		}
  2009		idx = strings.IndexRune(v[1:], rune(v[0]))
  2010		if idx == -1 {
  2011			return ""
  2012		}
  2013		return v[1 : idx+1]
  2014	}
  2015	

View as plain text