The following code does not work correctly:

package xml

import (
	"bytes"
	"fmt"
	"reflect"
	"strings"
)

// Marshal serializes a struct into XML bytes.
func Marshal(v interface{}, indent string) ([]byte, error) {
	var buf bytes.Buffer

	// Validate input
	rv := reflect.ValueOf(v)
	if rv.Kind() != reflect.Ptr || rv.Elem().Kind() != reflect.Struct {
		return nil, fmt.Errorf("marshal expects a pointer to a struct")
	}

	// Start marshaling process
	if err := marshalElement(rv.Elem(), &buf, indent); err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}

// marshalElement handles the serialization of a single struct element.
func marshalElement(rv reflect.Value, buf *bytes.Buffer, indent string) error {
	rt := rv.Type()

	// Retrieve XMLName or default
	xmlName := getXMLName(rv)
	if xmlName.Local == "" {
		return fmt.Errorf("missing XMLName on struct type: %s", rt)
	}

	// Start opening tag
	buf.WriteString("<")
	if xmlName.Prefix != "" {
		buf.WriteString(xmlName.Prefix + ":")
	}
	buf.WriteString(xmlName.Local)

	// Serialize attributes and namespaces
	if err := marshalAttributesAndNamespaces(rv, buf); err != nil {
		return err
	}

	// Collect child elements and inner XML
	children, innerXML, err := collectChildren(rv, buf, indent)
	if err != nil {
		return err
	}

	// Decide whether to self-close or add children/innerXML
	if len(children) == 0 && innerXML == "" {
		buf.WriteString("/>")
		return nil
	}

	buf.WriteString(">")

	if len(children) > 0 {
		// Add indentation for nested elements if needed
		if indent != "" {
			buf.WriteString("\n" + strings.Repeat(indent, 1))
		}

		// Recursively marshal child elements
		for _, child := range children {
			// Get the field name of the child element
			childFieldName := ""
			for i := 0; i < rt.NumField(); i++ {
				if rv.Field(i).Addr().Interface() == child.Addr().Interface() {
					childFieldName = rt.Field(i).Name
					break
				}
			}

			// If the child is from a slice, wrap its elements with the field name as the tag
			if child.Kind() == reflect.Struct && childFieldName != "" && rv.FieldByName(childFieldName).Kind() == reflect.Slice {
				// Open the parent tag
				buf.WriteString(fmt.Sprintf("<%s>", childFieldName))
				// Marshal each element in the slice
				for i := 0; i < rv.FieldByName(childFieldName).Len(); i++ {
					sliceElem := rv.FieldByName(childFieldName).Index(i)
					if err := marshalElement(sliceElem, buf, indent); err != nil {
						return err
					}
				}
				// Close the parent tag
				buf.WriteString(fmt.Sprintf("</%s>", childFieldName))
			} else {
				// Otherwise, marshal the child directly
				if err := marshalElement(child, buf, indent); err != nil {
					return err
				}
			}

			// Add indentation for closing tags if needed
			if indent != "" {
				buf.WriteString("\n" + strings.Repeat(indent, 1))
			}
		}
	} else if innerXML != "" {
		// Add inner XML only if there are no child elements
		buf.WriteString(innerXML)
	}

	// Close tag
	buf.WriteString("</")
	if xmlName.Prefix != "" {
		buf.WriteString(xmlName.Prefix + ":")
	}
	buf.WriteString(xmlName.Local + ">")

	return nil
}

// marshalAttributesAndNamespaces appends attributes and namespaces to the buffer.
func marshalAttributesAndNamespaces(rv reflect.Value, buf *bytes.Buffer) error {
	_ = rv.Type()

	// Handle XMLAttributes
	if attrsField := rv.FieldByName("XMLAttributes"); attrsField.IsValid() {
		if attrs, ok := attrsField.Interface().([]XMLAttribute); ok {
			for _, attr := range attrs {
				buf.WriteString(" ")
				if attr.Prefix != "" {
					buf.WriteString(attr.Prefix + ":")
				}
				buf.WriteString(fmt.Sprintf(`%s="%s"`, attr.LocalPart, escape(attr.Value)))
			}
		}
	}

	// Handle XMLNamespaces
	if nsField := rv.FieldByName("XMLNamespaces"); nsField.IsValid() {
		if namespaces, ok := nsField.Interface().([]XMLNamespace); ok {
			for _, ns := range namespaces {
				buf.WriteString(" xmlns")
				if ns.LocalPart != "" {
					buf.WriteString(":" + ns.LocalPart)
				}
				buf.WriteString(fmt.Sprintf(`="%s"`, escape(ns.Uri)))
			}
		}
	}

	return nil
}

// collectChildren gathers child elements and inner XML from the struct.
func collectChildren(rv reflect.Value, buf *bytes.Buffer, indent string) ([]reflect.Value, string, error) {
	var children []reflect.Value
	var innerXML string

	rt := rv.Type()
	for i := 0; i < rt.NumField(); i++ {
		field := rt.Field(i)
		value := rv.Field(i)

		// Skip XMLName, XMLAttributes, and XMLNamespaces
		if field.Type == reflect.TypeOf(XMLName{}) ||
			field.Name == "XMLAttributes" ||
			field.Name == "XMLNamespaces" {
			continue
		}

		xmlTag := field.Tag.Get("xml")
		var tagName string
		var tags map[string]struct{}

		if xmlTag != "" {
			tagParts := strings.Split(xmlTag, ",")
			tagName = strings.TrimSpace(tagParts[0])
			tags = parseTag(xmlTag)
		} else {
			// Default to field name if no xml tag
			tagName = field.Name
			tags = make(map[string]struct{})
		}

		// Handle slices (multiple child elements)
		if value.Kind() == reflect.Slice {
			for j := 0; j < value.Len(); j++ {
				elem := value.Index(j)
				// If the slice element is a struct, add it to children
				if elem.Kind() == reflect.Struct {
					children = append(children, elem)
				} else if elem.Kind() == reflect.Ptr && elem.Elem().Kind() == reflect.Struct {
					// If it's a pointer to a struct, dereference and add
					children = append(children, elem.Elem())
				}
			}
			continue
		}

		// Handle innerxml
		if _, ok := tags["innerxml"]; ok {
			if value.Kind() == reflect.String {
				innerXML = value.String()
			}
			continue
		}

		// Handle attributes (already processed)
		if _, ok := tags["attr"]; ok {
			continue
		}

		// Handle nested structs (single child element)
		if value.Kind() == reflect.Struct {
			children = append(children, value)
			continue
		}

		// Handle primitive types (string, int, etc.)
		// Serialize as child elements with text content
		if tagName != "" { // Only add if there's a tag name
			childValue := value.Interface()
			childXML := fmt.Sprintf("<%s>%v</%s>", tagName, childValue, tagName)
			innerXML += childXML
		}
	}

	return children, innerXML, nil
}

// escape escapes special XML characters in a string.
func escape(s string) string {
	var replacer = strings.NewReplacer(
		`&`, "&amp;",
		`"`, "&quot;",
		`'`, "&apos;",
		`<`, "&lt;",
		`>`, "&gt;",
	)
	return replacer.Replace(s)
}

// parseTag splits the XML tag into its components.
func parseTag(tag string) map[string]struct{} {
	parts := strings.Split(tag, ",")
	tagMap := make(map[string]struct{})
	for _, part := range parts[1:] { // Skip the first part (element name)
		tagMap[strings.TrimSpace(part)] = struct{}{}
	}
	return tagMap
}

// getXMLName retrieves the XMLName from the struct or defaults to struct name.
func getXMLName(rv reflect.Value) XMLName {
	if rv.CanInterface() {
		if marshaler, ok := rv.Interface().(XMLMarshaler); ok {
			return marshaler.XMLName()
		}
	}
	rt := rv.Type()

	// Attempt to find XMLName field
	for i := 0; i < rt.NumField(); i++ {
		field := rt.Field(i)
		if field.Type == reflect.TypeOf(XMLName{}) {
			xmlTag := field.Tag.Get("xml")
			if xmlTag != "" {
				// Split the tag into name and options
				parts := strings.Split(xmlTag, ",")
				tagName := strings.TrimSpace(parts[0])

				// Check for 'ns:' prefix in options
				for _, option := range parts[1:] {
					if strings.HasPrefix(option, "ns:") {
						nsParts := strings.Split(option, ":") // Skip 'ns:'
						if len(nsParts) == 2 {
							return XMLName{
								Prefix: nsParts[1],
								Local:  tagName,
							}
						} else {
							return XMLName{
								Prefix: nsParts[0],
								Local:  "", // Handle cases where only namespace is provided
							}
						}
					}
				}

				// If no 'ns:' is found, use the tag name as local name
				return XMLName{
					Prefix: "",
					Local:  tagName,
				}
			}

			// If no xml tag is set, check the XMLName field's value
			xmlNameVal := rv.Field(i).Interface().(XMLName)
			if xmlNameVal.Local != "" {
				return xmlNameVal
			}
		}
	}

	// No XMLName field or it's unset. Default to struct name.
	return XMLName{
		Prefix: "",
		Local:  rt.Name(),
	}
}


Using the following structure 
type Person struct {
	XMLName        XMLName `xml:"person"`
	XMLAttributes  []XMLAttribute
	XMLNamespaces  []XMLNamespace
	Name           string
	Age            int
	Addresses      []Address
	AdditionalInfo string `xml:"innerxml"`
}

type Address struct {
	XMLName XMLName `xml:"address"`
	Street  string
	City    string
}
	person := &Person{
		XMLAttributes: []XMLAttribute{
			{Prefix: "xsi", LocalPart: "type", Value: "personType"},
		},
		XMLNamespaces: []XMLNamespace{
			{LocalPart: "xsi", Uri: "http://www.w3.org/2001/XMLSchema-instance"},
		},
		Name:           "John Doe",
		Age:            30,
		AdditionalInfo: "<note>This is a person record.</note>",
		Addresses: []Address{
			{Street: "123 Main St", City: "Anytown"},
			{Street: "456 Maple Ave", City: "Othertown"},
		},
	}

I get the following output: <person xsi:type=\"personType\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><address><Street>123 Main St</Street><City>Anytown</City></address><address><Street>456 Maple Ave</Street><City>Othertown</City></address></person

There <addresses> Tag is completely missing. How to fix it.