// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package xml

import (
	
	
	
	
	
	
	
	
)

const (
	// Header is a generic XML header suitable for use with the output of Marshal.
	// This is not automatically added to any output of this package,
	// it is provided as a convenience.
	Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n"
)

// Marshal returns the XML encoding of v.
//
// Marshal handles an array or slice by marshaling each of the elements.
// Marshal handles a pointer by marshaling the value it points at or, if the
// pointer is nil, by writing nothing. Marshal handles an interface value by
// marshaling the value it contains or, if the interface value is nil, by
// writing nothing. Marshal handles all other data by writing one or more XML
// elements containing the data.
//
// The name for the XML elements is taken from, in order of preference:
//     - the tag on the XMLName field, if the data is a struct
//     - the value of the XMLName field of type Name
//     - the tag of the struct field used to obtain the data
//     - the name of the struct field used to obtain the data
//     - the name of the marshaled type
//
// The XML element for a struct contains marshaled elements for each of the
// exported fields of the struct, with these exceptions:
//     - the XMLName field, described above, is omitted.
//     - a field with tag "-" is omitted.
//     - a field with tag "name,attr" becomes an attribute with
//       the given name in the XML element.
//     - a field with tag ",attr" becomes an attribute with the
//       field name in the XML element.
//     - a field with tag ",chardata" is written as character data,
//       not as an XML element.
//     - a field with tag ",cdata" is written as character data
//       wrapped in one or more <![CDATA[ ... ]]> tags, not as an XML element.
//     - a field with tag ",innerxml" is written verbatim, not subject
//       to the usual marshaling procedure.
//     - a field with tag ",comment" is written as an XML comment, not
//       subject to the usual marshaling procedure. It must not contain
//       the "--" string within it.
//     - a field with a tag including the "omitempty" option is omitted
//       if the field value is empty. The empty values are false, 0, any
//       nil pointer or interface value, and any array, slice, map, or
//       string of length zero.
//     - an anonymous struct field is handled as if the fields of its
//       value were part of the outer struct.
//     - a field implementing Marshaler is written by calling its MarshalXML
//       method.
//     - a field implementing encoding.TextMarshaler is written by encoding the
//       result of its MarshalText method as text.
//
// If a field uses a tag "a>b>c", then the element c will be nested inside
// parent elements a and b. Fields that appear next to each other that name
// the same parent will be enclosed in one XML element.
//
// If the XML name for a struct field is defined by both the field tag and the
// struct's XMLName field, the names must match.
//
// See MarshalIndent for an example.
//
// Marshal will return an error if asked to marshal a channel, function, or map.
func ( interface{}) ([]byte, error) {
	var  bytes.Buffer
	if  := NewEncoder(&).Encode();  != nil {
		return nil, 
	}
	return .Bytes(), nil
}

// Marshaler is the interface implemented by objects that can marshal
// themselves into valid XML elements.
//
// MarshalXML encodes the receiver as zero or more XML elements.
// By convention, arrays or slices are typically encoded as a sequence
// of elements, one per entry.
// Using start as the element tag is not required, but doing so
// will enable Unmarshal to match the XML elements to the correct
// struct field.
// One common implementation strategy is to construct a separate
// value with a layout corresponding to the desired XML and then
// to encode it using e.EncodeElement.
// Another common strategy is to use repeated calls to e.EncodeToken
// to generate the XML output one token at a time.
// The sequence of encoded tokens must make up zero or more valid
// XML elements.
type Marshaler interface {
	MarshalXML(e *Encoder, start StartElement) error
}

// MarshalerAttr is the interface implemented by objects that can marshal
// themselves into valid XML attributes.
//
// MarshalXMLAttr returns an XML attribute with the encoded value of the receiver.
// Using name as the attribute name is not required, but doing so
// will enable Unmarshal to match the attribute to the correct
// struct field.
// If MarshalXMLAttr returns the zero attribute Attr{}, no attribute
// will be generated in the output.
// MarshalXMLAttr is used only for struct fields with the
// "attr" option in the field tag.
type MarshalerAttr interface {
	MarshalXMLAttr(name Name) (Attr, error)
}

// MarshalIndent works like Marshal, but each XML element begins on a new
// indented line that starts with prefix and is followed by one or more
// copies of indent according to the nesting depth.
func ( interface{}, ,  string) ([]byte, error) {
	var  bytes.Buffer
	 := NewEncoder(&)
	.Indent(, )
	if  := .Encode();  != nil {
		return nil, 
	}
	return .Bytes(), nil
}

// An Encoder writes XML data to an output stream.
type Encoder struct {
	p printer
}

// NewEncoder returns a new encoder that writes to w.
func ( io.Writer) *Encoder {
	 := &Encoder{printer{Writer: bufio.NewWriter()}}
	.p.encoder = 
	return 
}

// Indent sets the encoder to generate XML in which each element
// begins on a new indented line that starts with prefix and is followed by
// one or more copies of indent according to the nesting depth.
func ( *Encoder) (,  string) {
	.p.prefix = 
	.p.indent = 
}

// Encode writes the XML encoding of v to the stream.
//
// See the documentation for Marshal for details about the conversion
// of Go values to XML.
//
// Encode calls Flush before returning.
func ( *Encoder) ( interface{}) error {
	 := .p.marshalValue(reflect.ValueOf(), nil, nil)
	if  != nil {
		return 
	}
	return .p.Flush()
}

// EncodeElement writes the XML encoding of v to the stream,
// using start as the outermost tag in the encoding.
//
// See the documentation for Marshal for details about the conversion
// of Go values to XML.
//
// EncodeElement calls Flush before returning.
func ( *Encoder) ( interface{},  StartElement) error {
	 := .p.marshalValue(reflect.ValueOf(), nil, &)
	if  != nil {
		return 
	}
	return .p.Flush()
}

var (
	begComment  = []byte("<!--")
	endComment  = []byte("-->")
	endProcInst = []byte("?>")
)

// EncodeToken writes the given XML token to the stream.
// It returns an error if StartElement and EndElement tokens are not properly matched.
//
// EncodeToken does not call Flush, because usually it is part of a larger operation
// such as Encode or EncodeElement (or a custom Marshaler's MarshalXML invoked
// during those), and those will call Flush when finished.
// Callers that create an Encoder and then invoke EncodeToken directly, without
// using Encode or EncodeElement, need to call Flush when finished to ensure
// that the XML is written to the underlying writer.
//
// EncodeToken allows writing a ProcInst with Target set to "xml" only as the first token
// in the stream.
func ( *Encoder) ( Token) error {

	 := &.p
	switch t := .(type) {
	case StartElement:
		if  := .writeStart(&);  != nil {
			return 
		}
	case EndElement:
		if  := .writeEnd(.Name);  != nil {
			return 
		}
	case CharData:
		escapeText(, , false)
	case Comment:
		if bytes.Contains(, endComment) {
			return fmt.Errorf("xml: EncodeToken of Comment containing --> marker")
		}
		.WriteString("<!--")
		.Write()
		.WriteString("-->")
		return .cachedWriteError()
	case ProcInst:
		// First token to be encoded which is also a ProcInst with target of xml
		// is the xml declaration. The only ProcInst where target of xml is allowed.
		if .Target == "xml" && .Buffered() != 0 {
			return fmt.Errorf("xml: EncodeToken of ProcInst xml target only valid for xml declaration, first token encoded")
		}
		if !isNameString(.Target) {
			return fmt.Errorf("xml: EncodeToken of ProcInst with invalid Target")
		}
		if bytes.Contains(.Inst, endProcInst) {
			return fmt.Errorf("xml: EncodeToken of ProcInst containing ?> marker")
		}
		.WriteString("<?")
		.WriteString(.Target)
		if len(.Inst) > 0 {
			.WriteByte(' ')
			.Write(.Inst)
		}
		.WriteString("?>")
	case Directive:
		if !isValidDirective() {
			return fmt.Errorf("xml: EncodeToken of Directive containing wrong < or > markers")
		}
		.WriteString("<!")
		.Write()
		.WriteString(">")
	default:
		return fmt.Errorf("xml: EncodeToken of invalid token type")

	}
	return .cachedWriteError()
}

// isValidDirective reports whether dir is a valid directive text,
// meaning angle brackets are matched, ignoring comments and strings.
func isValidDirective( Directive) bool {
	var (
		     int
		   uint8
		 bool
	)
	for ,  := range  {
		switch {
		case :
			if  == '>' {
				if  := 1 +  - len(endComment);  >= 0 && bytes.Equal([:+1], endComment) {
					 = false
				}
			}
			// Just ignore anything in comment
		case  != 0:
			if  ==  {
				 = 0
			}
			// Just ignore anything within quotes
		case  == '\'' ||  == '"':
			 = 
		case  == '<':
			if +len(begComment) < len() && bytes.Equal([:+len(begComment)], begComment) {
				 = true
			} else {
				++
			}
		case  == '>':
			if  == 0 {
				return false
			}
			--
		}
	}
	return  == 0 &&  == 0 && !
}

// Flush flushes any buffered XML to the underlying writer.
// See the EncodeToken documentation for details about when it is necessary.
func ( *Encoder) () error {
	return .p.Flush()
}

type printer struct {
	*bufio.Writer
	encoder    *Encoder
	seq        int
	indent     string
	prefix     string
	depth      int
	indentedIn bool
	putNewline bool
	attrNS     map[string]string // map prefix -> name space
	attrPrefix map[string]string // map name space -> prefix
	prefixes   []string
	tags       []Name
}

// createAttrPrefix finds the name space prefix attribute to use for the given name space,
// defining a new prefix if necessary. It returns the prefix.
func ( *printer) ( string) string {
	if  := .attrPrefix[];  != "" {
		return 
	}

	// The "http://www.w3.org/XML/1998/namespace" name space is predefined as "xml"
	// and must be referred to that way.
	// (The "http://www.w3.org/2000/xmlns/" name space is also predefined as "xmlns",
	// but users should not be trying to use that one directly - that's our job.)
	if  == xmlURL {
		return xmlPrefix
	}

	// Need to define a new name space.
	if .attrPrefix == nil {
		.attrPrefix = make(map[string]string)
		.attrNS = make(map[string]string)
	}

	// Pick a name. We try to use the final element of the path
	// but fall back to _.
	 := strings.TrimRight(, "/")
	if  := strings.LastIndex(, "/");  >= 0 {
		 = [+1:]
	}
	if  == "" || !isName([]byte()) || strings.Contains(, ":") {
		 = "_"
	}
	// xmlanything is reserved and any variant of it regardless of
	// case should be matched, so:
	//    (('X'|'x') ('M'|'m') ('L'|'l'))
	// See Section 2.3 of https://www.w3.org/TR/REC-xml/
	if len() >= 3 && strings.EqualFold([:3], "xml") {
		 = "_" + 
	}
	if .attrNS[] != "" {
		// Name is taken. Find a better one.
		for .seq++; ; .seq++ {
			if  :=  + "_" + strconv.Itoa(.seq); .attrNS[] == "" {
				 = 
				break
			}
		}
	}

	.attrPrefix[] = 
	.attrNS[] = 

	.WriteString(`xmlns:`)
	.WriteString()
	.WriteString(`="`)
	EscapeText(, []byte())
	.WriteString(`" `)

	.prefixes = append(.prefixes, )

	return 
}

// deleteAttrPrefix removes an attribute name space prefix.
func ( *printer) ( string) {
	delete(.attrPrefix, .attrNS[])
	delete(.attrNS, )
}

func ( *printer) () {
	.prefixes = append(.prefixes, "")
}

func ( *printer) () {
	for len(.prefixes) > 0 {
		 := .prefixes[len(.prefixes)-1]
		.prefixes = .prefixes[:len(.prefixes)-1]
		if  == "" {
			break
		}
		.deleteAttrPrefix()
	}
}

var (
	marshalerType     = reflect.TypeOf((*Marshaler)(nil)).Elem()
	marshalerAttrType = reflect.TypeOf((*MarshalerAttr)(nil)).Elem()
	textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
)

// marshalValue writes one or more XML elements representing val.
// If val was obtained from a struct field, finfo must have its details.
func ( *printer) ( reflect.Value,  *fieldInfo,  *StartElement) error {
	if  != nil && .Name.Local == "" {
		return fmt.Errorf("xml: EncodeElement of StartElement with missing name")
	}

	if !.IsValid() {
		return nil
	}
	if  != nil && .flags&fOmitEmpty != 0 && isEmptyValue() {
		return nil
	}

	// Drill into interfaces and pointers.
	// This can turn into an infinite loop given a cyclic chain,
	// but it matches the Go 1 behavior.
	for .Kind() == reflect.Interface || .Kind() == reflect.Ptr {
		if .IsNil() {
			return nil
		}
		 = .Elem()
	}

	 := .Kind()
	 := .Type()

	// Check for marshaler.
	if .CanInterface() && .Implements(marshalerType) {
		return .marshalInterface(.Interface().(Marshaler), defaultStart(, , ))
	}
	if .CanAddr() {
		 := .Addr()
		if .CanInterface() && .Type().Implements(marshalerType) {
			return .marshalInterface(.Interface().(Marshaler), defaultStart(.Type(), , ))
		}
	}

	// Check for text marshaler.
	if .CanInterface() && .Implements(textMarshalerType) {
		return .marshalTextInterface(.Interface().(encoding.TextMarshaler), defaultStart(, , ))
	}
	if .CanAddr() {
		 := .Addr()
		if .CanInterface() && .Type().Implements(textMarshalerType) {
			return .marshalTextInterface(.Interface().(encoding.TextMarshaler), defaultStart(.Type(), , ))
		}
	}

	// Slices and arrays iterate over the elements. They do not have an enclosing tag.
	if ( == reflect.Slice ||  == reflect.Array) && .Elem().Kind() != reflect.Uint8 {
		for ,  := 0, .Len();  < ; ++ {
			if  := .(.Index(), , );  != nil {
				return 
			}
		}
		return nil
	}

	,  := getTypeInfo()
	if  != nil {
		return 
	}

	// Create start element.
	// Precedence for the XML element name is:
	// 0. startTemplate
	// 1. XMLName field in underlying struct;
	// 2. field name/tag in the struct field; and
	// 3. type name
	var  StartElement

	if  != nil {
		.Name = .Name
		.Attr = append(.Attr, .Attr...)
	} else if .xmlname != nil {
		 := .xmlname
		if .name != "" {
			.Name.Space, .Name.Local = .xmlns, .name
		} else {
			 := .value(, dontInitNilPointers)
			if ,  := .Interface().(Name);  && .Local != "" {
				.Name = 
			}
		}
	}
	if .Name.Local == "" &&  != nil {
		.Name.Space, .Name.Local = .xmlns, .name
	}
	if .Name.Local == "" {
		 := .Name()
		if  == "" {
			return &UnsupportedTypeError{}
		}
		.Name.Local = 
	}

	// Attributes
	for  := range .fields {
		 := &.fields[]
		if .flags&fAttr == 0 {
			continue
		}
		 := .value(, dontInitNilPointers)

		if .flags&fOmitEmpty != 0 && isEmptyValue() {
			continue
		}

		if .Kind() == reflect.Interface && .IsNil() {
			continue
		}

		 := Name{Space: .xmlns, Local: .name}
		if  := .marshalAttr(&, , );  != nil {
			return 
		}
	}

	if  := .writeStart(&);  != nil {
		return 
	}

	if .Kind() == reflect.Struct {
		 = .marshalStruct(, )
	} else {
		, ,  := .marshalSimple(, )
		if  != nil {
			 = 
		} else if  != nil {
			EscapeText(, )
		} else {
			.EscapeString()
		}
	}
	if  != nil {
		return 
	}

	if  := .writeEnd(.Name);  != nil {
		return 
	}

	return .cachedWriteError()
}

// marshalAttr marshals an attribute with the given name and value, adding to start.Attr.
func ( *printer) ( *StartElement,  Name,  reflect.Value) error {
	if .CanInterface() && .Type().Implements(marshalerAttrType) {
		,  := .Interface().(MarshalerAttr).MarshalXMLAttr()
		if  != nil {
			return 
		}
		if .Name.Local != "" {
			.Attr = append(.Attr, )
		}
		return nil
	}

	if .CanAddr() {
		 := .Addr()
		if .CanInterface() && .Type().Implements(marshalerAttrType) {
			,  := .Interface().(MarshalerAttr).MarshalXMLAttr()
			if  != nil {
				return 
			}
			if .Name.Local != "" {
				.Attr = append(.Attr, )
			}
			return nil
		}
	}

	if .CanInterface() && .Type().Implements(textMarshalerType) {
		,  := .Interface().(encoding.TextMarshaler).MarshalText()
		if  != nil {
			return 
		}
		.Attr = append(.Attr, Attr{, string()})
		return nil
	}

	if .CanAddr() {
		 := .Addr()
		if .CanInterface() && .Type().Implements(textMarshalerType) {
			,  := .Interface().(encoding.TextMarshaler).MarshalText()
			if  != nil {
				return 
			}
			.Attr = append(.Attr, Attr{, string()})
			return nil
		}
	}

	// Dereference or skip nil pointer, interface values.
	switch .Kind() {
	case reflect.Ptr, reflect.Interface:
		if .IsNil() {
			return nil
		}
		 = .Elem()
	}

	// Walk slices.
	if .Kind() == reflect.Slice && .Type().Elem().Kind() != reflect.Uint8 {
		 := .Len()
		for  := 0;  < ; ++ {
			if  := .(, , .Index());  != nil {
				return 
			}
		}
		return nil
	}

	if .Type() == attrType {
		.Attr = append(.Attr, .Interface().(Attr))
		return nil
	}

	, ,  := .marshalSimple(.Type(), )
	if  != nil {
		return 
	}
	if  != nil {
		 = string()
	}
	.Attr = append(.Attr, Attr{, })
	return nil
}

// defaultStart returns the default start element to use,
// given the reflect type, field info, and start template.
func defaultStart( reflect.Type,  *fieldInfo,  *StartElement) StartElement {
	var  StartElement
	// Precedence for the XML element name is as above,
	// except that we do not look inside structs for the first field.
	if  != nil {
		.Name = .Name
		.Attr = append(.Attr, .Attr...)
	} else if  != nil && .name != "" {
		.Name.Local = .name
		.Name.Space = .xmlns
	} else if .Name() != "" {
		.Name.Local = .Name()
	} else {
		// Must be a pointer to a named type,
		// since it has the Marshaler methods.
		.Name.Local = .Elem().Name()
	}
	return 
}

// marshalInterface marshals a Marshaler interface value.
func ( *printer) ( Marshaler,  StartElement) error {
	// Push a marker onto the tag stack so that MarshalXML
	// cannot close the XML tags that it did not open.
	.tags = append(.tags, Name{})
	 := len(.tags)

	 := .MarshalXML(.encoder, )
	if  != nil {
		return 
	}

	// Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark.
	if len(.tags) >  {
		return fmt.Errorf("xml: %s.MarshalXML wrote invalid XML: <%s> not closed", receiverType(), .tags[len(.tags)-1].Local)
	}
	.tags = .tags[:-1]
	return nil
}

// marshalTextInterface marshals a TextMarshaler interface value.
func ( *printer) ( encoding.TextMarshaler,  StartElement) error {
	if  := .writeStart(&);  != nil {
		return 
	}
	,  := .MarshalText()
	if  != nil {
		return 
	}
	EscapeText(, )
	return .writeEnd(.Name)
}

// writeStart writes the given start element.
func ( *printer) ( *StartElement) error {
	if .Name.Local == "" {
		return fmt.Errorf("xml: start tag with no name")
	}

	.tags = append(.tags, .Name)
	.markPrefix()

	.writeIndent(1)
	.WriteByte('<')
	.WriteString(.Name.Local)

	if .Name.Space != "" {
		.WriteString(` xmlns="`)
		.EscapeString(.Name.Space)
		.WriteByte('"')
	}

	// Attributes
	for ,  := range .Attr {
		 := .Name
		if .Local == "" {
			continue
		}
		.WriteByte(' ')
		if .Space != "" {
			.WriteString(.createAttrPrefix(.Space))
			.WriteByte(':')
		}
		.WriteString(.Local)
		.WriteString(`="`)
		.EscapeString(.Value)
		.WriteByte('"')
	}
	.WriteByte('>')
	return nil
}

func ( *printer) ( Name) error {
	if .Local == "" {
		return fmt.Errorf("xml: end tag with no name")
	}
	if len(.tags) == 0 || .tags[len(.tags)-1].Local == "" {
		return fmt.Errorf("xml: end tag </%s> without start tag", .Local)
	}
	if  := .tags[len(.tags)-1];  !=  {
		if .Local != .Local {
			return fmt.Errorf("xml: end tag </%s> does not match start tag <%s>", .Local, .Local)
		}
		return fmt.Errorf("xml: end tag </%s> in namespace %s does not match start tag <%s> in namespace %s", .Local, .Space, .Local, .Space)
	}
	.tags = .tags[:len(.tags)-1]

	.writeIndent(-1)
	.WriteByte('<')
	.WriteByte('/')
	.WriteString(.Local)
	.WriteByte('>')
	.popPrefix()
	return nil
}

func ( *printer) ( reflect.Type,  reflect.Value) (string, []byte, error) {
	switch .Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return strconv.FormatInt(.Int(), 10), nil, nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return strconv.FormatUint(.Uint(), 10), nil, nil
	case reflect.Float32, reflect.Float64:
		return strconv.FormatFloat(.Float(), 'g', -1, .Type().Bits()), nil, nil
	case reflect.String:
		return .String(), nil, nil
	case reflect.Bool:
		return strconv.FormatBool(.Bool()), nil, nil
	case reflect.Array:
		if .Elem().Kind() != reflect.Uint8 {
			break
		}
		// [...]byte
		var  []byte
		if .CanAddr() {
			 = .Slice(0, .Len()).Bytes()
		} else {
			 = make([]byte, .Len())
			reflect.Copy(reflect.ValueOf(), )
		}
		return "", , nil
	case reflect.Slice:
		if .Elem().Kind() != reflect.Uint8 {
			break
		}
		// []byte
		return "", .Bytes(), nil
	}
	return "", nil, &UnsupportedTypeError{}
}

var ddBytes = []byte("--")

// indirect drills into interfaces and pointers, returning the pointed-at value.
// If it encounters a nil interface or pointer, indirect returns that nil value.
// This can turn into an infinite loop given a cyclic chain,
// but it matches the Go 1 behavior.
func indirect( reflect.Value) reflect.Value {
	for .Kind() == reflect.Interface || .Kind() == reflect.Ptr {
		if .IsNil() {
			return 
		}
		 = .Elem()
	}
	return 
}

func ( *printer) ( *typeInfo,  reflect.Value) error {
	 := parentStack{p: }
	for  := range .fields {
		 := &.fields[]
		if .flags&fAttr != 0 {
			continue
		}
		 := .value(, dontInitNilPointers)
		if !.IsValid() {
			// The field is behind an anonymous struct field that's
			// nil. Skip it.
			continue
		}

		switch .flags & fMode {
		case fCDATA, fCharData:
			 := EscapeText
			if .flags&fMode == fCDATA {
				 = emitCDATA
			}
			if  := .trim(.parents);  != nil {
				return 
			}
			if .CanInterface() && .Type().Implements(textMarshalerType) {
				,  := .Interface().(encoding.TextMarshaler).MarshalText()
				if  != nil {
					return 
				}
				if  := (, );  != nil {
					return 
				}
				continue
			}
			if .CanAddr() {
				 := .Addr()
				if .CanInterface() && .Type().Implements(textMarshalerType) {
					,  := .Interface().(encoding.TextMarshaler).MarshalText()
					if  != nil {
						return 
					}
					if  := (, );  != nil {
						return 
					}
					continue
				}
			}

			var  [64]byte
			 = indirect()
			switch .Kind() {
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				if  := (, strconv.AppendInt([:0], .Int(), 10));  != nil {
					return 
				}
			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
				if  := (, strconv.AppendUint([:0], .Uint(), 10));  != nil {
					return 
				}
			case reflect.Float32, reflect.Float64:
				if  := (, strconv.AppendFloat([:0], .Float(), 'g', -1, .Type().Bits()));  != nil {
					return 
				}
			case reflect.Bool:
				if  := (, strconv.AppendBool([:0], .Bool()));  != nil {
					return 
				}
			case reflect.String:
				if  := (, []byte(.String()));  != nil {
					return 
				}
			case reflect.Slice:
				if ,  := .Interface().([]byte);  {
					if  := (, );  != nil {
						return 
					}
				}
			}
			continue

		case fComment:
			if  := .trim(.parents);  != nil {
				return 
			}
			 = indirect()
			 := .Kind()
			if !( == reflect.String ||  == reflect.Slice && .Type().Elem().Kind() == reflect.Uint8) {
				return fmt.Errorf("xml: bad type for comment field of %s", .Type())
			}
			if .Len() == 0 {
				continue
			}
			.writeIndent(0)
			.WriteString("<!--")
			 := false
			 := false
			switch  {
			case reflect.String:
				 := .String()
				 = strings.Contains(, "--")
				 = [len()-1] == '-'
				if ! {
					.WriteString()
				}
			case reflect.Slice:
				 := .Bytes()
				 = bytes.Contains(, ddBytes)
				 = [len()-1] == '-'
				if ! {
					.Write()
				}
			default:
				panic("can't happen")
			}
			if  {
				return fmt.Errorf(`xml: comments must not contain "--"`)
			}
			if  {
				// "--->" is invalid grammar. Make it "- -->"
				.WriteByte(' ')
			}
			.WriteString("-->")
			continue

		case fInnerXML:
			 = indirect()
			 := .Interface()
			switch raw := .(type) {
			case []byte:
				.Write()
				continue
			case string:
				.WriteString()
				continue
			}

		case fElement, fElement | fAny:
			if  := .trim(.parents);  != nil {
				return 
			}
			if len(.parents) > len(.stack) {
				if .Kind() != reflect.Ptr && .Kind() != reflect.Interface || !.IsNil() {
					if  := .push(.parents[len(.stack):]);  != nil {
						return 
					}
				}
			}
		}
		if  := .marshalValue(, , nil);  != nil {
			return 
		}
	}
	.trim(nil)
	return .cachedWriteError()
}

// return the bufio Writer's cached write error
func ( *printer) () error {
	,  := .Write(nil)
	return 
}

func ( *printer) ( int) {
	if len(.prefix) == 0 && len(.indent) == 0 {
		return
	}
	if  < 0 {
		.depth--
		if .indentedIn {
			.indentedIn = false
			return
		}
		.indentedIn = false
	}
	if .putNewline {
		.WriteByte('\n')
	} else {
		.putNewline = true
	}
	if len(.prefix) > 0 {
		.WriteString(.prefix)
	}
	if len(.indent) > 0 {
		for  := 0;  < .depth; ++ {
			.WriteString(.indent)
		}
	}
	if  > 0 {
		.depth++
		.indentedIn = true
	}
}

type parentStack struct {
	p     *printer
	stack []string
}

// trim updates the XML context to match the longest common prefix of the stack
// and the given parents. A closing tag will be written for every parent
// popped. Passing a zero slice or nil will close all the elements.
func ( *parentStack) ( []string) error {
	 := 0
	for ;  < len() &&  < len(.stack); ++ {
		if [] != .stack[] {
			break
		}
	}
	for  := len(.stack) - 1;  >= ; -- {
		if  := .p.writeEnd(Name{Local: .stack[]});  != nil {
			return 
		}
	}
	.stack = .stack[:]
	return nil
}

// push adds parent elements to the stack and writes open tags.
func ( *parentStack) ( []string) error {
	for  := 0;  < len(); ++ {
		if  := .p.writeStart(&StartElement{Name: Name{Local: []}});  != nil {
			return 
		}
	}
	.stack = append(.stack, ...)
	return nil
}

// UnsupportedTypeError is returned when Marshal encounters a type
// that cannot be converted into XML.
type UnsupportedTypeError struct {
	Type reflect.Type
}

func ( *UnsupportedTypeError) () string {
	return "xml: unsupported type: " + .Type.String()
}

func isEmptyValue( reflect.Value) bool {
	switch .Kind() {
	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
		return .Len() == 0
	case reflect.Bool:
		return !.Bool()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return .Int() == 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return .Uint() == 0
	case reflect.Float32, reflect.Float64:
		return .Float() == 0
	case reflect.Interface, reflect.Ptr:
		return .IsNil()
	}
	return false
}