/**
  * Renders the xsl object to a string. Global and local data are merged
  * and extracted to create local variables within the xsl file.
  *
  *     $output = $xsl->render();
  *
  * [!!] Global variables with the same key name as local variables will be
  * overwritten by the local variable.
  *
  * @param    string  xsl filename
  * @return   string
  * @throws   Kohana_Exception
  */
 public function render($file = NULL)
 {
     if ($file !== NULL) {
         $this->set_filename($file);
     }
     if (empty($this->_file)) {
         throw new Kohana_Exception('You must set the file to use within your xsl before rendering');
     }
     if (Xslt::$_global_data) {
         // Import the global xsl variables to local namespace and maintain references
         $this->_data = array_merge(Xslt::$_global_data, $this->_data);
     }
     // Create the XML DOM
     $this->_dom = new DomDocument('1.0', 'UTF-8');
     $this->_dom->preserveWhiteSpace = FALSE;
     $this->_dom->formatOutput = TRUE;
     // echo $this->array2xml( $this->_data );
     $this->_dom->loadXML($this->array2xml($this->_data));
     // Link the xml and xsl
     $this->_dom->insertBefore($this->_dom->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="' . $this->_file . '"'));
     // Load the xsl
     $xslt = new DOMDocument();
     $doc = array("content" => Xslt::capture($this->_file), "pattern" => "/<!DOCTYPE (.*) PUBLIC \"(.*)\" \"(.*)\">/i", "match" => array(), "method" => "xml", "public" => "", "system" => "");
     preg_match($doc["pattern"], $doc["content"], $match);
     if (!empty($match)) {
         $doc["content"] = preg_replace($doc["pattern"], "", $doc["content"]);
         $doc["match"] = $match;
         $doc["method"] = $doc["match"][1];
         $doc["public"] = "doctype-public=\"" . $doc["match"][2] . "\"";
         $doc["system"] = "doctype-system=\"" . $doc["match"][3] . "\"";
     }
     $doc["content"] = $this->get_includes($doc["content"]);
     $xslt->loadXML("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\t\t\t<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\t\t\t<xsl:output\n\t\t\t\tmethod=\"xml\"\n\t\t\t\tencoding=\"" . Kohana::$charset . "\"\n\t\t\t\tomit-xml-declaration=\"no\"\n\t\t\t\t" . $doc["public"] . "\n\t\t\t\t" . $doc["system"] . "\n\t\t\t\tindent=\"no\"\n\t\t\t\t/>\n\n\t\t\t<xsl:template match=\"/root\">" . $doc["content"] . "</xsl:template></xsl:stylesheet>");
     // Process XSLT
     $proc = new xsltprocessor();
     $proc->importStyleSheet($xslt);
     // Return HTML
     $return_html = $proc->transformToDoc($this->_dom)->saveXML();
     $return_html = html_entity_decode($return_html);
     return str_replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n", "", $return_html);
 }