FIXME ver como aplicar esto a {@link XMLSimpleContentHandler}
975266
public void onStartObject() {
		this.currentObjectKey = this.currentLocalName;
		if (this.firstObjectKey == null && this.currentLocalName != null) {
			this.firstObjectKey = this.currentObjectKey;
		}

		if (this.currentObjectKey != null) {
			stackObjectKey.push(this.currentObjectKey);
		} else {
			if (!stackObjectKey.isEmpty()) {
				this.currentObjectKey = stackObjectKey.peek();
			} else {
				this.currentObjectKey = this.firstObjectKey;
			}
		}
	}
443147
private static function fixXmlLocation(string $schemaSource, string $xmlUri): string
    {
        $newPath = str_replace('\\', '/', __DIR__).'/../Resources/schemas/xml.xsd';
        $parts = explode('/', $newPath);
        $locationstart = 'file:///';
        if (0 === stripos($newPath, 'phar://')) {
            $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
            if ($tmpfile) {
                copy($newPath, $tmpfile);
                $parts = explode('/', str_replace('\\', '/', $tmpfile));
            } else {
                array_shift($parts);
                $locationstart = 'phar:///';
            }
        }

        $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
        $newPath = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts));

        return str_replace($xmlUri, $newPath, $schemaSource);
    }
991117
function xmlDefaultHandler($parser,$data)
		{
			//strip '<!--' and '-->' off comments
			$data = repl(array("&lt;!--", "--&gt;"), "", htmlspecialchars($data));
			$count = $this->xmlCount - 1;
			if(!empty($this->xmlDData[$count])) $this->xmlDData[$count] .= $data;
			else $this->xmlDData[$count] = $data;
		}
217530
private void setupParse ()
  {
    XMLReader p = getParent();
    if (p == null) {
      throw new NullPointerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_PARENT_FOR_FILTER, null)); //"No parent for filter");
    }
    
    ContentHandler ch = m_transformer.getInputContentHandler();
//    if(ch instanceof SourceTreeHandler)
//      ((SourceTreeHandler)ch).setUseMultiThreading(true);
    p.setContentHandler(ch);
    p.setEntityResolver(this);
    p.setDTDHandler(this);
    p.setErrorHandler(this);
  }
1365098
synchronized ContentHandler getContentHandler()
        throws IOException
    {
        String contentType = stripOffParameters(getContentType());
        ContentHandler handler = null;
        if (contentType == null) {
            if ((contentType = guessContentTypeFromName(url.getFile())) == null) {
                contentType = guessContentTypeFromStream(getInputStream());
            }
        }

        if (contentType == null) {
            return UnknownContentHandler.INSTANCE;
        }
        try {
            handler = (ContentHandler) handlers.get(contentType);
            if (handler != null)
                return handler;
        } catch(Exception e) {
        }

        if (factory != null)
            handler = factory.createContentHandler(contentType);
        if (handler == null) {
            try {
                handler = lookupContentHandlerClassFor(contentType);
            } catch(Exception e) {
                e.printStackTrace();
                handler = UnknownContentHandler.INSTANCE;
            }
            handlers.put(contentType, handler);
        }
        return handler;
    }
970045
public void appendXMLToContentEntry(final XMLUtil util,
                                        final Appendable appendable) throws IOException {
        this.appendPreamble(util, appendable);
        this.appendRows(util, appendable);
        this.appendPostamble(appendable);
    }
1374415
function xmlStartElement($parser,$name,$attribs)
		{
			$this->xmlAttrib[$this->xmlCount] = $attribs;
			$this->xmlName[$this->xmlCount] = $name;
			$this->xmlSData[$this->xmlCount] = '$this->makeTableHeader("xml", "xml element", 2);';
			$this->xmlSData[$this->xmlCount] .= '$this->makeTDHeader("xml", "xmlName");';
			$this->xmlSData[$this->xmlCount] .= 'echo "<strong>' . $this->xmlName[$this->xmlCount] . '</strong>".$this->closeTDRow();';
			$this->xmlSData[$this->xmlCount] .= '$this->makeTDHeader("xml", "xmlAttributes");';
			if(count($attribs) > 0) $this->xmlSData[$this->xmlCount] .= '$this->varIsArray($this->xmlAttrib[' . $this->xmlCount . ']);';
			else $this->xmlSData[$this->xmlCount] .= 'echo "&nbsp;";';
			$this->xmlSData[$this->xmlCount] .= 'echo $this->closeTDRow();';
			$this->xmlCount++;
		}
1013924
public static XMLReader createXMLReader() throws SAXException, ParserConfigurationException, FactoryConfigurationError {
        try {
            return (XMLReader) AccessController.doPrivileged(new PrivilegedExceptionAction() {
                public Object run() throws SAXException, ParserConfigurationException, FactoryConfigurationError {
                    Thread currThread = Thread.currentThread();
                    ClassLoader oldLoader = currThread.getContextClassLoader();
                    currThread.setContextClassLoader(ParserFactory.class.getClassLoader());
                    try {
                        /**
                         * Changed to use pluggable parser version. Needed for JDK 1.4.1
                         */
                        return SAXParserFactory.newInstance().newSAXParser().getXMLReader();
                        //return XMLReaderFactory.createXMLReader();
                    }
                                        finally {
                                            currThread.setContextClassLoader(oldLoader);
                                        }
                                    }
            });
        } catch (PrivilegedActionException pae) {
            Throwable t = pae.getCause();
            if (t instanceof SAXException) {
                throw (SAXException) t;
            } else if (t instanceof ParserConfigurationException) {
                throw (ParserConfigurationException) t;
            } else if (t instanceof FactoryConfigurationError) {
                throw (FactoryConfigurationError) t;
            }
        }
        return null;
    }
494331
public function setDefaultXmlDecoder()
    {
        $this->xmlDecoder = function ($response) {
            $xml_obj = @simplexml_load_string($response);
            if (!($xml_obj === false)) {
                $response = $xml_obj;
            }
            return $response;
        };
    }
1034105
public void setXMLContent(byte[] xmlContent) {
        if (m_dsType == DS_TYPE.INLINE_XML) {
            ((DatastreamXMLMetadata)m_ds).xmlContent = xmlContent;
            ((DatastreamXMLMetadata)m_ds).DSSize = (xmlContent != null) ? xmlContent.length : -1;
        } else if (m_dsType == DS_TYPE.MANAGED) {
            ByteArrayInputStream bais = new ByteArrayInputStream(xmlContent);
            MIMETypedStream s = new MIMETypedStream("text/xml", bais, null,xmlContent.length);
            try {
                ((DatastreamManagedContent)m_ds).putContentStream(s);
            } catch (StreamIOException e) {
                throw new RuntimeException("Unable to update managed datastream contents", e);
            }
        } else
            // coding error if trying to use other datastream type
            throw new RuntimeException("XML datastreams must be of type Managed or Inline");
    }
372418
public function create()
    {
        $fs = new Filesystem();

        if (!$this->sourceDir) {
            throw new \Exception('O diretório de código fonte "singular.directory.src" da aplicação não foi definido!');
        }

        $migrationDir = $this->getMigrationDir();

        if (!$fs->exists($migrationDir)) {
            throw new \Exception(sprintf('O diretório de migration não existe!'));
        }

        $timestamp = time();

        $aplicacoes = $this->getAplicacoesToMigration();

        if (count($aplicacoes) > 0) {
            $template = file_get_contents(
                __DIR__.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR."app_migration.tpl"
            );

            $template = str_replace('$TIMESTAMP',$timestamp, $template);
            $template = str_replace('$APLICACOES', $this->arrayToString($aplicacoes, $timestamp) , $template);

            $dt = new \DateTime('now', new \DateTimeZone('UTC'));
            $date = $dt->format('YmdHis');

            file_put_contents($migrationDir.DIRECTORY_SEPARATOR.$date.'_insere_registros_aplicacoes_'.$timestamp.'.php', $template);
        }

        $modulos = $this->getModulosToMigration();

        if (count($modulos) > 0) {
            $template = file_get_contents(
                __DIR__.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR."mod_migration.tpl"
            );

            $template = str_replace('$TIMESTAMP',$timestamp, $template);
            $template = str_replace('$MODULOS', $this->arrayToString($modulos, $timestamp) , $template);

            sleep(1);

            $dt = new \DateTime('now', new \DateTimeZone('UTC'));
            $date = $dt->format('YmdHis');

            file_put_contents($migrationDir.DIRECTORY_SEPARATOR.$date.'_insere_registros_modulos_'.$timestamp.'.php', $template);
        }

        $this->clearMigrations();

        return count($modulos) + count($aplicacoes);
    }
627325
@Override
    public XMLEventReader2 createXMLEventReader(URL src)
        throws XMLStreamException
    {
        /* true for auto-close, since caller has no access to the underlying
         * input stream created from the URL
         */
        return new WstxEventReader(createEventAllocator(),
                                   createSR(createPrivateConfig(), src, true, true));
    }
378898
@Override
    public XMLEventReader createXMLEventReader(InputStream in)
        throws XMLStreamException
    {
        // false for auto-close, since caller has access to the input stream
        return new WstxEventReader(createEventAllocator(),
        		createSR(null, in, null, true, false));
    }
503915
public int resolveAndValidateElement()
        throws XMLStreamException
    {
        if (mDepth == 0) { // just a simple sanity check
            throw new IllegalStateException("Calling validate() on empty stack.");
        }
        AttributeCollector ac = mAttrCollector;

        // Any namespace declarations?
        {
            int nsCount = ac.getNsCount();
            if (nsCount > 0) {
                /* let's first invalidate old (possibly) shared ns ctxt too,
                 * if we had one; new one can be created at a later point
                 */
                mLastNsContext = null;

                boolean internNsUris = mConfig.willInternNsURIs();
                for (int i = 0; i < nsCount; ++i) {
                    Attribute ns = ac.resolveNamespaceDecl(i, internNsUris);
                    String nsUri = ns.mNamespaceURI;
                    // note: for namespaces, prefix is stored as local name
                    String prefix = ns.mLocalName;

                    /* 18-Jul-2004, TSa: Need to check that 'xml' and 'xmlns'
                     *   prefixes are not re-defined (and 'xmlns' not even
                     *   defined to its correct ns).
                     */
                    if (prefix == "xmlns") {
                        // xmlns can never be declared, even to its correct URI
                        mReporter.throwParseError(ErrorConsts.ERR_NS_REDECL_XMLNS);
                    } else if (prefix == "xml") {
                        // whereas xml is ok, as long as it's same URI:
                        if (!nsUri.equals(XMLConstants.XML_NS_URI)) {
                            mReporter.throwParseError(ErrorConsts.ERR_NS_REDECL_XML,
                                                      nsUri, null);
                        }
                        /* 09-Feb-2006, TSa: Hmmh. Now, should this explicit
                         *   xml declaration be visible to the app? SAX API
                         *   seem to ignore it.
                         */
                        //mNamespaces.addStrings(prefix, nsUri);
                    } else { // ok, valid prefix, so far
                        /* 17-Mar-2006, TSa: Unbinding default NS needs to
                         *    result in null being added:
                         */
                        if (nsUri == null || nsUri.length() == 0) {
                            nsUri = XmlConsts.DEFAULT_NAMESPACE_URI;
                        }
                        // The default ns binding needs special handling:
                        if (prefix == null) {
                            mCurrElement.mDefaultNsURI = nsUri;
                        }

                        /* But then let's ensure that URIs matching xml
                         * and xmlns are not being bound to anything else
                         */
                        if (internNsUris) { // identity comparison is ok:
                            if (nsUri == XMLConstants.XML_NS_URI) {
                                mReporter.throwParseError(ErrorConsts.ERR_NS_REDECL_XML_URI, prefix, null);
                            } else if (nsUri == XMLConstants.XMLNS_ATTRIBUTE_NS_URI) {
                                mReporter.throwParseError(ErrorConsts.ERR_NS_REDECL_XMLNS_URI);
                            }
                        } else { // need to check equals()
                            if (nsUri.equals(XMLConstants.XML_NS_URI)) {
                                mReporter.throwParseError(ErrorConsts.ERR_NS_REDECL_XML_URI, prefix, null);
                            } else if (nsUri.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
                                mReporter.throwParseError(ErrorConsts.ERR_NS_REDECL_XMLNS_URI);
                            }
                        }
                        /* and at any rate, binding needs to be added, to
                         * be visible to the app (including def ns):
                         */
                        mNamespaces.addStrings(prefix, nsUri);
                    }
                }
            }
        }

        /* 20-Feb-2006, TSa: Any attribute defaults for namespace declaration
         *   pseudo-attributes?
         */
        if (mMayHaveNsDefaults) {
            mNsDefaultProvider.checkNsDefaults(this);
        }

        // Then, let's set element's namespace, if any:
        String prefix = mCurrElement.mPrefix;
        String ns;

        if (prefix == null) { // use default NS, if any
            ns = mCurrElement.mDefaultNsURI;
        } else if (prefix == "xml") {
            ns = XMLConstants.XML_NS_URI;
        } else {
            // Need to find namespace with the prefix:
            ns = mNamespaces.findLastFromMap(prefix);
            /* 07-Sep-2007, TSa: "no namespace" should now be indicated
             *   by an empty string, however, due to historical reasons
             *   let's be bit defensive and allow nulls for the same too
             */
            if (ns == null || ns.length() == 0) {
                mReporter.throwParseError(ErrorConsts.ERR_NS_UNDECLARED, prefix, null);
            }
        }
        mCurrElement.mNamespaceURI = ns;

        // And finally, resolve attributes' namespaces too:
        int xmlidIx = ac.resolveNamespaces(mReporter, mNamespaces);
        mIdAttrIndex = xmlidIx;

        XMLValidator vld = mValidator;
        /* If we have no validator(s), nothing more to do,
         * except perhaps little bit of Xml:id handling:
         */
        if (vld == null) { // no validator in use
            if (xmlidIx >= 0) { // need to normalize xml:id, still?
                ac.normalizeSpacesInValue(xmlidIx);
            }
            return XMLValidator.CONTENT_ALLOW_ANY_TEXT;
        }

        // Otherwise need to call relevant validation methods.

        /* First, a call to check if the element itself may be acceptable
         * within structure:
         */
        vld.validateElementStart
            (mCurrElement.mLocalName, mCurrElement.mNamespaceURI, mCurrElement.mPrefix);

        // Then attributes, if any:
        int attrLen = ac.getCount();
        if (attrLen > 0) {
            for (int i = 0; i < attrLen; ++i) {
                ac.validateAttribute(i, mValidator);
            }
        }

        /* And finally let's wrap things up to see what textual content
         * is allowed as child content, if any:
         */
        return mValidator.validateElementAndAttributes();
    }
1159050
public function zSignXML($xmldoc, $root, $node, $objSSLPriKey)
    {
        $nsDSIG = 'http://www.w3.org/2000/09/xmldsig#';
        $nsCannonMethod = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
        $nsSignatureMethod = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1';
        $nsTransformMethod1 = 'http://www.w3.org/2000/09/xmldsig#enveloped-signature';
        $nsTransformMethod2 = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
        $nsDigestMethod = 'http://www.w3.org/2000/09/xmldsig#sha1';
        //pega o atributo id do node a ser assinado
        $idSigned = (trim($node->getAttribute('Id') == null)
                    ? $node->getAttribute('id')
                    : $node->getAttribute('Id'));
        //extrai os dados da tag para uma string na forma canonica
        $dados = $node->C14N(true, false, null, null);
        //calcular o hash dos dados
        $hashValue = hash('sha1', $dados, true);
        //converter o hash para base64
        $digValue = base64_encode($hashValue);
        //cria o node <Signature>
        $signatureNode = $xmldoc->createElementNS($nsDSIG, 'Signature');
        //adiciona a tag <Signature> ao node raiz
        $root->appendChild($signatureNode);
        //cria o node <SignedInfo>
        $signedInfoNode = $xmldoc->createElement('SignedInfo');
        //adiciona o node <SignedInfo> ao <Signature>
        $signatureNode->appendChild($signedInfoNode);
        //cria no node com o método de canonização dos dados
        $canonicalNode = $xmldoc->createElement('CanonicalizationMethod');
        //adiona o <CanonicalizationMethod> ao node <SignedInfo>
        $signedInfoNode->appendChild($canonicalNode);
        //seta o atributo ao node <CanonicalizationMethod>
        $canonicalNode->setAttribute('Algorithm', $nsCannonMethod);
        //cria o node <SignatureMethod>
        $signatureMethodNode = $xmldoc->createElement('SignatureMethod');
        //adiciona o node <SignatureMethod> ao node <SignedInfo>
        $signedInfoNode->appendChild($signatureMethodNode);
        //seta o atributo Algorithm ao node <SignatureMethod>
        $signatureMethodNode->setAttribute('Algorithm', $nsSignatureMethod);
        //cria o node <Reference>
        $referenceNode = $xmldoc->createElement('Reference');
        //adiciona o node <Reference> ao node <SignedInfo>
        $signedInfoNode->appendChild($referenceNode);
        //seta o atributo URI a node <Reference>
        $idSigned == null ? $referenceNode->setAttribute('URI', '' . $idSigned)
                          : $referenceNode->setAttribute('URI', '#' . $idSigned);
        //cria o node <Transforms>
        $transformsNode = $xmldoc->createElement('Transforms');
        //adiciona o node <Transforms> ao node <Reference>
        $referenceNode->appendChild($transformsNode);
        //cria o primeiro node <Transform> OBS: no singular
        $transfNode1 = $xmldoc->createElement('Transform');
        //adiciona o primeiro node <Transform> ao node <Transforms>
        $transformsNode->appendChild($transfNode1);
        //set o atributo Algorithm ao primeiro node <Transform>
        $transfNode1->setAttribute('Algorithm', $nsTransformMethod1);
        //cria outro node <Transform> OBS: no singular
        $transfNode2 = $xmldoc->createElement('Transform');
        //adiciona o segundo node <Transform> ao node <Transforms>
        $transformsNode->appendChild($transfNode2);
        //set o atributo Algorithm ao segundo node <Transform>
        $transfNode2->setAttribute('Algorithm', $nsTransformMethod2);
        //cria o node <DigestMethod>
        $digestMethodNode = $xmldoc->createElement('DigestMethod');
        //adiciona o node <DigestMethod> ao node <Reference>
        $referenceNode->appendChild($digestMethodNode);
        //seta o atributo Algorithm ao node <DigestMethod>
        $digestMethodNode->setAttribute('Algorithm', $nsDigestMethod);
        //cria o node <DigestValue>
        $digestValueNode = $xmldoc->createElement('DigestValue', $digValue);
        //adiciona o node <DigestValue> ao node <Reference>
        $referenceNode->appendChild($digestValueNode);
        //extrai node <SignedInfo> para uma string na sua forma canonica
        $cnSignedInfoNode = $signedInfoNode->C14N(true, false, null, null);
        //cria uma variavel vazia que receberá a assinatura
        $signature = '';
        //calcula a assinatura do node canonizado <SignedInfo>
        //usando a chave privada em formato PEM
        if (! openssl_sign($cnSignedInfoNode, $signature, $objSSLPriKey)) {
            $msg = "Houve erro durante a assinatura digital.\n";
            $this->zGetOpenSSLError($msg);
        }
        //converte a assinatura em base64
        $signatureValue = base64_encode($signature);
        //cria o node <SignatureValue>
        $signatureValueNode = $xmldoc->createElement('SignatureValue', $signatureValue);
        //adiciona o node <SignatureValue> ao node <Signature>
        $signatureNode->appendChild($signatureValueNode);
        //cria o node <KeyInfo>
        $keyInfoNode = $xmldoc->createElement('KeyInfo');
        //adiciona o node <KeyInfo> ao node <Signature>
        $signatureNode->appendChild($keyInfoNode);
        //cria o node <X509Data>
        $x509DataNode = $xmldoc->createElement('X509Data');
        //adiciona o node <X509Data> ao node <KeyInfo>
        $keyInfoNode->appendChild($x509DataNode);
        //remove linhas desnecessárias do certificado
        $pubKeyClean = $this->zCleanPubKey();
        //cria o node <X509Certificate>
        $x509CertificateNode = $xmldoc->createElement('X509Certificate', $pubKeyClean);
        //adiciona o node <X509Certificate> ao node <X509Data>
        $x509DataNode->appendChild($x509CertificateNode);
        //salva o xml completo em uma string
        $xmlResp = $xmldoc->saveXML();
        //retorna o documento assinado
        return $xmlResp;
    }
471937
private static function deserializePlayReadyContentKey($xmlElement)
    {
        $type = $xmlElement->attributes(Resources::XSI_XML_NAMESPACE)->type;

        if ($type == 'ContentEncryptionKeyFromHeader') {
            return new ContentEncryptionKeyFromHeader();
        }

        if ($type == 'ContentEncryptionKeyFromKeyIdentifier') {
            return new ContentEncryptionKeyFromKeyIdentifier($xmlElement->KeyIdentifier);
        }

        throw new \RuntimeException("Unknown PlayReadyContentKey type={$type}");
    }
194227
protected void prepareXMLReader() throws VerifierConfigurationException {
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);
			reader = factory.newSAXParser().getXMLReader();
		} catch( SAXException e ) {
			throw new VerifierConfigurationException(e);
		} catch( ParserConfigurationException pce ) {
			throw new VerifierConfigurationException(pce);
		}
	}