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

View as plain text