func (e *Element) readFrom(ri io.Reader, settings ReadSettings) (n int64, err error) {
	r := newCountReader(ri)
	dec := xml.NewDecoder(r)
	dec.CharsetReader = settings.CharsetReader
	dec.Strict = !settings.Permissive
	dec.Entity = settings.Entity
	var stack stack
	stack.push(e)
	for {
		t, err := dec.RawToken()
		switch {
		case err == io.EOF:
			return r.bytes, nil
		case err != nil:
			return r.bytes, err
		case stack.empty():
			return r.bytes, ErrXML
		}
		top := stack.peek().(*Element)
		switch t := t.(type) {
		case xml.StartElement:
			e := newElement(t.Name.Space, t.Name.Local, top)
			for _, a := range t.Attr {
				e.createAttr(a.Name.Space, a.Name.Local, a.Value, e)
			}
			stack.push(e)
		case xml.EndElement:
			stack.pop()
		case xml.CharData:
			data := string(t)
			var flags charDataFlags
			if isWhitespace(data) {
				flags = whitespaceFlag
			}
			newCharData(data, flags, top)
		case xml.Comment:
			newComment(string(t), top)
		case xml.Directive:
			newDirective(string(t), top)
		case xml.ProcInst:
			newProcInst(t.Target, string(t.Inst), top)
		}
	}
}
ReadFrom reads XML from the reader r and stores the result as a new child
of element e.
package etree
import (
	"bufio"
	"bytes"
	"encoding/xml"
	"errors"
	"io"
	"os"
	"sort"
	"strings"
)
const (
	NoIndent = -1
)
var ErrXML = errors.New("etree: invalid XML format")
type ReadSettings struct {
	CharsetReader func(charset string, input io.Reader) (io.Reader, error)
	Permissive bool
	Entity map[string]string
}
func newReadSettings() ReadSettings {
	return ReadSettings{
		CharsetReader: func(label string, input io.Reader) (io.Reader, error) {
			return input, nil
		},
		Permissive: false,
	}
}
type WriteSettings struct {
	CanonicalEndTags bool
	CanonicalText bool
	CanonicalAttrVal bool
	UseCRLF bool
}
func newWriteSettings() WriteSettings {
	return WriteSettings{
		CanonicalEndTags: false,
		CanonicalText:    false,
		CanonicalAttrVal: false,
		UseCRLF:          false,
	}
}
type Token interface {
	Parent() *Element
	Index() int
	dup(parent *Element) Token
	setParent(parent *Element)
	setIndex(index int)
	writeTo(w *bufio.Writer, s *WriteSettings)
}
type Document struct {
	Element
	ReadSettings  ReadSettings
	WriteSettings WriteSettings
}
type Element struct {
	Space, Tag string    
	Attr       []Attr    
	Child      []Token   
	parent     *Element  
	index      int       
}
type Attr struct {
	Space, Key string    
	Value      string    
	element    *Element  
}
type charDataFlags uint8
const (
	whitespaceFlag charDataFlags = 1 << iota
	cdataFlag
)
type CharData struct {
	Data   string
	parent *Element
	index  int
	flags  charDataFlags
}
type Comment struct {
	Data   string
	parent *Element
	index  int
}
type Directive struct {
	Data   string
	parent *Element
	index  int
}
type ProcInst struct {
	Target string
	Inst   string
	parent *Element
	index  int
}
func NewDocument() *Document {
	return &Document{
		Element{Child: make([]Token, 0)},
		newReadSettings(),
		newWriteSettings(),
	}
}
func (d *Document) Copy() *Document {
	return &Document{*(d.dup(nil).(*Element)), d.ReadSettings, d.WriteSettings}
}
func (d *Document) Root() *Element {
	for _, t := range d.Child {
		if c, ok := t.(*Element); ok {
			return c
		}
	}
	return nil
}
func (d *Document) SetRoot(e *Element) {
	if e.parent != nil {
		e.parent.RemoveChild(e)
	}
	p := &d.Element
	e.setParent(p)
	for i, t := range p.Child {
		if _, ok := t.(*Element); ok {
			t.setParent(nil)
			t.setIndex(-1)
			p.Child[i] = e
			e.setIndex(i)
			return
		}
	}
	p.addChild(e)
}
func (d *Document) ReadFrom(r io.Reader) (n int64, err error) {
	return d.Element.readFrom(r, d.ReadSettings)
}
func (d *Document) ReadFromFile(filename string) error {
	f, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer f.Close()
	_, err = d.ReadFrom(f)
	return err
}
func (d *Document) ReadFromBytes(b []byte) error {
	_, err := d.ReadFrom(bytes.NewReader(b))
	return err
}
func (d *Document) ReadFromString(s string) error {
	_, err := d.ReadFrom(strings.NewReader(s))
	return err
}
func (d *Document) WriteTo(w io.Writer) (n int64, err error) {
	cw := newCountWriter(w)
	b := bufio.NewWriter(cw)
	for _, c := range d.Child {
		c.writeTo(b, &d.WriteSettings)
	}
	err, n = b.Flush(), cw.bytes
	return
}
func (d *Document) WriteToFile(filename string) error {
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer f.Close()
	_, err = d.WriteTo(f)
	return err
}
func (d *Document) WriteToBytes() (b []byte, err error) {
	var buf bytes.Buffer
	if _, err = d.WriteTo(&buf); err != nil {
		return
	}
	return buf.Bytes(), nil
}
func (d *Document) WriteToString() (s string, err error) {
	var b []byte
	if b, err = d.WriteToBytes(); err != nil {
		return
	}
	return string(b), nil
}
type indentFunc func(depth int) string
func (d *Document) Indent(spaces int) {
	var indent indentFunc
	switch {
	case spaces < 0:
		indent = func(depth int) string { return "" }
	case d.WriteSettings.UseCRLF == true:
		indent = func(depth int) string { return indentCRLF(depth*spaces, indentSpaces) }
	default:
		indent = func(depth int) string { return indentLF(depth*spaces, indentSpaces) }
	}
	d.Element.indent(0, indent)
}
func (d *Document) IndentTabs() {
	var indent indentFunc
	switch d.WriteSettings.UseCRLF {
	case true:
		indent = func(depth int) string { return indentCRLF(depth, indentTabs) }
	default:
		indent = func(depth int) string { return indentLF(depth, indentTabs) }
	}
	d.Element.indent(0, indent)
}
func NewElement(tag string) *Element {
	space, stag := spaceDecompose(tag)
	return newElement(space, stag, nil)
}
func newElement(space, tag string, parent *Element) *Element {
	e := &Element{
		Space:  space,
		Tag:    tag,
		Attr:   make([]Attr, 0),
		Child:  make([]Token, 0),
		parent: parent,
		index:  -1,
	}
	if parent != nil {
		parent.addChild(e)
	}
	return e
}
func (e *Element) Copy() *Element {
	return e.dup(nil).(*Element)
}
func (e *Element) FullTag() string {
	if e.Space == "" {
		return e.Tag
	}
	return e.Space + ":" + e.Tag
}
func (e *Element) NamespaceURI() string {
	if e.Space == "" {
		return e.findDefaultNamespaceURI()
	}
	return e.findLocalNamespaceURI(e.Space)
}
func (e *Element) findLocalNamespaceURI(prefix string) string {
	for _, a := range e.Attr {
		if a.Space == "xmlns" && a.Key == prefix {
			return a.Value
		}
	}
	if e.parent == nil {
		return ""
	}
	return e.parent.findLocalNamespaceURI(prefix)
}
func (e *Element) findDefaultNamespaceURI() string {
	for _, a := range e.Attr {
		if a.Space == "" && a.Key == "xmlns" {
			return a.Value
		}
	}
	if e.parent == nil {
		return ""
	}
	return e.parent.findDefaultNamespaceURI()
}
func (e *Element) hasText() bool {
	if len(e.Child) == 0 {
		return false
	}
	_, ok := e.Child[0].(*CharData)
	return ok
}
func (e *Element) namespacePrefix() string {
	return e.Space
}
func (e *Element) name() string {
	return e.Tag
}
func (e *Element) Text() string {
	if len(e.Child) == 0 {
		return ""
	}
	text := ""
	for _, ch := range e.Child {
		if cd, ok := ch.(*CharData); ok {
			if text == "" {
				text = cd.Data
			} else {
				text = text + cd.Data
			}
		} else {
			break
		}
	}
	return text
}
func (e *Element) SetText(text string) {
	e.replaceText(0, text, 0)
}
func (e *Element) SetCData(text string) {
	e.replaceText(0, text, cdataFlag)
}
func (e *Element) Tail() string {
	if e.Parent() == nil {
		return ""
	}
	p := e.Parent()
	i := e.Index()
	text := ""
	for _, ch := range p.Child[i+1:] {
		if cd, ok := ch.(*CharData); ok {
			if text == "" {
				text = cd.Data
			} else {
				text = text + cd.Data
			}
		} else {
			break
		}
	}
	return text
}
func (e *Element) SetTail(text string) {
	if e.Parent() == nil {
		return
	}
	p := e.Parent()
	p.replaceText(e.Index()+1, text, 0)
}
func (e *Element) replaceText(i int, text string, flags charDataFlags) {
	end := e.findTermCharDataIndex(i)
	switch {
	case end == i:
		if text != "" {
			cd := newCharData(text, flags, nil)
			e.InsertChildAt(i, cd)
		}
	case end == i+1:
		if text == "" {
			e.RemoveChildAt(i)
		} else {
			cd := e.Child[i].(*CharData)
			cd.Data, cd.flags = text, flags
		}
	default:
		if text == "" {
			copy(e.Child[i:], e.Child[end:])
			removed := end - i
			e.Child = e.Child[:len(e.Child)-removed]
			for j := i; j < len(e.Child); j++ {
				e.Child[j].setIndex(j)
			}
		} else {
			cd := e.Child[i].(*CharData)
			cd.Data, cd.flags = text, flags
			copy(e.Child[i+1:], e.Child[end:])
			removed := end - (i + 1)
			e.Child = e.Child[:len(e.Child)-removed]
			for j := i + 1; j < len(e.Child); j++ {
				e.Child[j].setIndex(j)
			}
		}
	}
}
func (e *Element) findTermCharDataIndex(start int) int {
	for i := start; i < len(e.Child); i++ {
		if _, ok := e.Child[i].(*CharData); !ok {
			return i
		}
	}
	return len(e.Child)
}
func (e *Element) CreateElement(tag string) *Element {
	space, stag := spaceDecompose(tag)
	return newElement(space, stag, e)
}
func (e *Element) AddChild(t Token) {
	if t.Parent() != nil {
		t.Parent().RemoveChild(t)
	}
	t.setParent(e)
	e.addChild(t)
}
func (e *Element) InsertChild(ex Token, t Token) {
	if ex == nil || ex.Parent() != e {
		e.AddChild(t)
		return
	}
	if t.Parent() != nil {
		t.Parent().RemoveChild(t)
	}
	t.setParent(e)
	i := ex.Index()
	e.Child = append(e.Child, nil)
	copy(e.Child[i+1:], e.Child[i:])
	e.Child[i] = t
	for j := i; j < len(e.Child); j++ {
		e.Child[j].setIndex(j)
	}
}
func (e *Element) InsertChildAt(index int, t Token) {
	if index >= len(e.Child) {
		e.AddChild(t)
		return
	}
	if t.Parent() != nil {
		if t.Parent() == e && t.Index() > index {
			index--
		}
		t.Parent().RemoveChild(t)
	}
	t.setParent(e)
	e.Child = append(e.Child, nil)
	copy(e.Child[index+1:], e.Child[index:])
	e.Child[index] = t
	for j := index; j < len(e.Child); j++ {
		e.Child[j].setIndex(j)
	}
}
func (e *Element) RemoveChild(t Token) Token {
	if t.Parent() != e {
		return nil
	}
	return e.RemoveChildAt(t.Index())
}
func (e *Element) RemoveChildAt(index int) Token {
	if index >= len(e.Child) {
		return nil
	}
	t := e.Child[index]
	for j := index + 1; j < len(e.Child); j++ {
		e.Child[j].setIndex(j - 1)
	}
	e.Child = append(e.Child[:index], e.Child[index+1:]...)
	t.setIndex(-1)
	t.setParent(nil)
	return t
}