function toXML($encoding = "UTF-8", $indent = true, $single = true)
    {
        $this->marcxml->setIndent($indent);
        if ($single) {
            $this->marcxml->startElement("collection");
            $this->marcxml->writeAttribute("xmlns", "http://www.loc.gov/MARC21/slim");
            $this->marcxml->startElement("record");
        } else {
            $this->marcxml->startElement("record");
            $this->marcxml->writeAttribute("xmlns", "http://www.loc.gov/MARC21/slim");
        }
        

        // MARCXML schema has some strict requirements
        // We'll set reasonable defaults to avoid invalid MARCXML
        $xmlLeader = $this->getLeader();

        // Record status
        if ($xmlLeader[5] == " ") {
            // Default to "n" (new record)
            $xmlLeader[5] = "n";
        }

        // Type of record
        if ($xmlLeader[6] == " ") {
            // Default to "a" (language material)
            $xmlLeader[6] = "a";
        }

        $this->marcxml->writeElement("leader", $xmlLeader);

        foreach ($this->fields as $field) {
            if (!$field->isEmpty()) {
                switch(get_class($field)) {
                case "File_MARC_Control_Field":
                    $this->marcxml->startElement("controlfield");
                    $this->marcxml->writeAttribute("tag", $field->getTag());
                    $this->marcxml->text($field->getData());
                    $this->marcxml->endElement(); // end control field
                    break;

                case "File_MARC_Data_Field":
                    $this->marcxml->startElement("datafield");
                    $this->marcxml->writeAttribute("tag", $field->getTag());
                    $this->marcxml->writeAttribute("ind1", $field->getIndicator(1));
                    $this->marcxml->writeAttribute("ind2", $field->getIndicator(2));
                    foreach ($field->getSubfields() as $subfield) {
                        $this->marcxml->startElement("subfield");
                        $this->marcxml->writeAttribute("code", $subfield->getCode());
                        $this->marcxml->text($subfield->getData());
                        $this->marcxml->endElement(); // end subfield
                    }
                    $this->marcxml->endElement(); // end data field
                    break;
                }
            }
        }

        $this->marcxml->endElement(); // end record
        if ($single) {
            $this->marcxml->endElement(); // end collection
            $this->marcxml->endDocument();
        }
        return $this->marcxml->outputMemory();
    }