domparser.cpp

来自「IBM的解析xml的工具Xerces的源代码」· C++ 代码 · 共 1,464 行 · 第 1/3 页

CPP
1,464
字号
}// ---------------------------------------------------------------------------//  DOMParser: Progressive parse methods// ---------------------------------------------------------------------------bool DOMParser::parseFirst( const   XMLCh* const    systemId                           ,       XMLPScanToken&  toFill){    //    //  Avoid multiple entrance. We cannot enter here while a regular parse    //  is in progress.    //    if (fParseInProgress)        ThrowXMLwithMemMgr(IOException, XMLExcepts::Gen_ParseInProgress, fMemoryManager);    return fScanner->scanFirst(systemId, toFill);}bool DOMParser::parseFirst( const   char* const         systemId                           ,       XMLPScanToken&      toFill){    //    //  Avoid multiple entrance. We cannot enter here while a regular parse    //  is in progress.    //    if (fParseInProgress)        ThrowXMLwithMemMgr(IOException, XMLExcepts::Gen_ParseInProgress, fMemoryManager);    return fScanner->scanFirst(systemId, toFill);}bool DOMParser::parseFirst( const   InputSource&    source                           ,       XMLPScanToken&  toFill){    //    //  Avoid multiple entrance. We cannot enter here while a regular parse    //  is in progress.    //    if (fParseInProgress)        ThrowXMLwithMemMgr(IOException, XMLExcepts::Gen_ParseInProgress, fMemoryManager);    return fScanner->scanFirst(source, toFill);}bool DOMParser::parseNext(XMLPScanToken& token){    return fScanner->scanNext(token);}void DOMParser::parseReset(XMLPScanToken& token){    // Reset the scanner, and then reset the parser    fScanner->scanReset(token);    reset();}// ---------------------------------------------------------------------------//  DOMParser: Implementation of the XMLErrorReporter interface// ---------------------------------------------------------------------------void DOMParser::error(  const   unsigned int                code                      , const XMLCh* const                msgDomain                      , const XMLErrorReporter::ErrTypes  errType                      , const XMLCh* const                errorText                      , const XMLCh* const                systemId                      , const XMLCh* const                publicId                      , const XMLSSize_t                  lineNum                      , const XMLSSize_t                  colNum){    SAXParseException toThrow = SAXParseException        (        errorText        , publicId        , systemId        , lineNum        , colNum        , fMemoryManager        );    //    //  If there is an error handler registered, call it, otherwise ignore    //  all but the fatal errors.    //    if (!fErrorHandler)    {        if (errType == XMLErrorReporter::ErrType_Fatal)            throw toThrow;        return;    }    if (errType == XMLErrorReporter::ErrType_Warning)        fErrorHandler->warning(toThrow);    else if (errType >= XMLErrorReporter::ErrType_Fatal)        fErrorHandler->fatalError(toThrow);    else        fErrorHandler->error(toThrow);}void DOMParser::resetErrors(){}// ---------------------------------------------------------------------------//  DOMParser: Implementation of XMLEntityHandler interface// ---------------------------------------------------------------------------InputSource*DOMParser::resolveEntity(const XMLCh* const publicId,                         const XMLCh* const systemId,                         const XMLCh* const baseURI){    //    //  Just map it to the SAX entity resolver. If there is not one installed,    //  return a null pointer to cause the default resolution.    //    if (fEntityResolver)        return fEntityResolver->resolveEntity(publicId, systemId);    return 0;}InputSource* DOMParser::resolveEntity(XMLResourceIdentifier* resourceIdentifier) {    //    //  Just map it to the SAX entity resolver. If there is not one installed,    //  return a null pointer to cause the default resolution.    //    if (fEntityResolver)        return fEntityResolver->resolveEntity(resourceIdentifier->getPublicId(),                                                 resourceIdentifier->getSystemId());    if (fXMLEntityResolver)        return fXMLEntityResolver->resolveEntity(resourceIdentifier);    return 0;}// ---------------------------------------------------------------------------//  DOMParser: Implementation of XMLDocumentHandler interface// ---------------------------------------------------------------------------void DOMParser::docCharacters(  const   XMLCh* const    chars                              , const unsigned int    length                              , const bool            cdataSection){    // Ignore chars outside of content    if (!fWithinElement)        return;    if (cdataSection == true)    {        DOM_CDATASection node = fDocument.createCDATASection            (            DOMString(chars, length)            );        fCurrentParent.appendChild(node);        fCurrentNode = node;    }    else    {        if (fCurrentNode.getNodeType() == DOM_Node::TEXT_NODE)        {            DOM_Text node = (DOM_Text&)fCurrentNode;            node.appendData(DOMString(chars, length));        }        else        {            DOM_Text node = fDocument.createTextNode(DOMString(chars, length));            fCurrentParent.appendChild(node);            fCurrentNode = node;        }    }}void DOMParser::docComment(const XMLCh* const comment){    DOM_Comment dcom = fDocument.createComment(comment);    fCurrentParent.appendChild(dcom);    fCurrentNode = dcom;}void DOMParser::docPI(  const   XMLCh* const    target                      , const XMLCh* const    data){    DOM_ProcessingInstruction pi = fDocument.createProcessingInstruction        (        target        , data        );    fCurrentParent.appendChild(pi);    fCurrentNode = pi;}void DOMParser::endEntityReference(const XMLEntityDecl& entDecl){    if (fCreateEntityReferenceNodes == true)    {        if (fCurrentParent.getNodeType() == DOM_Node::ENTITY_REFERENCE_NODE) {            ((DOM_EntityReference&)fCurrentParent).fImpl->setReadOnly(true, true);        }        fCurrentParent = fNodeStack->pop();        fCurrentNode   = fCurrentParent;    }}void DOMParser::endElement( const   XMLElementDecl&    elemDecl                           , const unsigned int        urlId                           , const bool                isRoot                           , const XMLCh* const        elemPrefix){    fCurrentNode   = fCurrentParent;    fCurrentParent = fNodeStack->pop();    // If we've hit the end of content, clear the flag    if (fNodeStack->empty())        fWithinElement = false;}void DOMParser::ignorableWhitespace(const   XMLCh* const    chars                                    , const unsigned int    length                                    , const bool            cdataSection){    // Ignore chars before the root element    if (!fWithinElement || !fIncludeIgnorableWhitespace)        return;    if (fCurrentNode.getNodeType() == DOM_Node::TEXT_NODE)    {        DOM_Text node = (DOM_Text&)fCurrentNode;        node.appendData(DOMString(chars, length));    }    else    {        DOM_Text node = fDocument.createTextNode(DOMString(chars, length));        TextImpl *text = (TextImpl *) node.fImpl;        text -> setIgnorableWhitespace(true);        fCurrentParent.appendChild(node);        fCurrentNode = node;    }}void DOMParser::resetDocument(){    //    //  The reset methods are called before a new parse event occurs.    //  Reset this parsers state to clear out anything that may be left    //  from a previous use, in particular the DOM document itself.    //    this->reset();}void DOMParser::startDocument(){    // Just set the document as the current parent and current node    fCurrentParent = fDocument;    fCurrentNode   = fDocument;    // set DOM error checking off    fDocument.setErrorChecking(false);}void DOMParser::endDocument(){    // set DOM error checking back on    fDocument.setErrorChecking(true);}void DOMParser::startElement(const  XMLElementDecl&         elemDecl                             , const unsigned int            urlId                             , const XMLCh* const            elemPrefix                             , const RefVectorOf<XMLAttr>&   attrList                             , const unsigned int            attrCount                             , const bool                    isEmpty                             , const bool                    isRoot){    DOM_Element     elem;    DocumentImpl    *docImpl = (DocumentImpl *)fDocument.fImpl;    if (fScanner -> getDoNamespaces()) {    //DOM Level 2, doNamespaces on        XMLBuffer buf(1023, fMemoryManager);        DOMString namespaceURI = 0;        DOMString elemQName = 0;        if (urlId != fScanner->getEmptyNamespaceId()) {  //TagName has a prefix            fScanner->getURIText(urlId, buf);   //get namespaceURI            namespaceURI = DOMString(buf.getRawBuffer());            if (elemPrefix && *elemPrefix) {                elemQName.appendData(elemPrefix);                elemQName.appendData(chColon);            }        }        elemQName.appendData(elemDecl.getBaseName());        elem = fDocument.createElementNS(namespaceURI, elemQName);        ElementImpl *elemImpl = (ElementImpl *) elem.fImpl;        for (unsigned int index = 0; index < attrCount; ++index) {            static const XMLCh XMLNS[] = {            chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chNull            };            const XMLAttr* oneAttrib = attrList.elementAt(index);            unsigned int attrURIId = oneAttrib -> getURIId();            namespaceURI = 0;            if (!XMLString::compareString(oneAttrib -> getName(), XMLNS))    //for xmlns=...                attrURIId = fScanner->getXMLNSNamespaceId();            if (attrURIId != fScanner->getEmptyNamespaceId()) {  //TagName has a prefix                fScanner->getURIText(attrURIId, buf);   //get namespaceURI                namespaceURI = DOMString(buf.getRawBuffer());            }            AttrImpl *attr = elemImpl->setAttributeNS(namespaceURI, oneAttrib -> getQName(),            oneAttrib -> getValue());            // Attributes of type ID.  If this is one, add it to the hashtable of IDs            //   that is constructed for use by GetElementByID().            //            if (oneAttrib->getType()==XMLAttDef::ID)            {                if (docImpl->fNodeIDMap == 0)                    docImpl->fNodeIDMap = new (fMemoryManager) NodeIDMap(500, fMemoryManager);                docImpl->fNodeIDMap->add(attr);                attr->isIdAttr(true);            }            attr->setSpecified(oneAttrib->getSpecified());        }    }    else {    //DOM Level 1        elem = fDocument.createElement(elemDecl.getFullName());        ElementImpl *elemImpl = (ElementImpl *) elem.fImpl;        for (unsigned int index = 0; index < attrCount; ++index) {            const XMLAttr* oneAttrib = attrList.elementAt(index);            AttrImpl *attr = elemImpl->setAttribute(oneAttrib->getName(), oneAttrib->getValue());            attr->setSpecified(oneAttrib->getSpecified());            // Attributes of type ID.  If this is one, add it to the hashtable of IDs            //   that is constructed for use by GetElementByID().            //            if (oneAttrib->getType()==XMLAttDef::ID)            {                if (docImpl->fNodeIDMap == 0)                    docImpl->fNodeIDMap = new (fMemoryManager) NodeIDMap(500, fMemoryManager);                docImpl->fNodeIDMap->add(attr);                attr->isIdAttr(true);            }        }    }    fCurrentParent.appendChild(elem);    fNodeStack->push(fCurrentParent);    fCurrentParent = elem;    fCurrentNode = elem;    fWithinElement = true;    // If an empty element, do end right now (no endElement() will be called)    if (isEmpty)        endElement(elemDecl, urlId, isRoot, elemPrefix);}void DOMParser::startEntityReference(const XMLEntityDecl& entDecl){    if (fCreateEntityReferenceNodes == true)    {		DOMString entName(entDecl.getName());        DOM_EntityReference er = fDocument.createEntityReference(entName);        //set the readOnly flag to false before appending node, will be reset in endEntityReference        er.fImpl->setReadOnly(false, true);        fCurrentParent.appendChild(er);        fNodeStack->push(fCurrentParent);        fCurrentParent = er;        fCurrentNode = er;		// this entityRef needs to be stored in Entity map too.        // We'd decide later whether the entity nodes should be created by a        // separated method in parser or not. For now just stick it in if        // the ref nodes are created		EntityImpl* entity = (EntityImpl*)fDocumentType->entities->getNamedItem(entName);		entity->setEntityRef((EntityReferenceImpl*)er.fImpl);    }}void DOMParser::XMLDecl(const   XMLCh* const version                        , const XMLCh* const encoding                        , const XMLCh* const standalone                        , const XMLCh* const actualEncStr){    //This is a non-standard extension to creating XMLDecl type nodes and attching to DOM Tree    // currently this flag it set to false unless user explicitly asks for it    // Needs to be revisited after W3C specs are laid out on this issue.    if (fToCreateXMLDeclTypeNode) {        DOMString ver(version);        DOMString enc(encoding);        DOMString isStd(standalone);        DOM_XMLDecl xmlDecl = fDocument.createXMLDecl(ver, enc, isStd);        fCurrentParent.appendChild(xmlDecl);    }}// ---------------------------------------------------------------------------//  DOMParser: Deprecated methods// ---------------------------------------------------------------------------bool DOMParser::getDoValidation() const{    //    //  We don't want to tie the public parser classes to the enum used    //  by the scanner, so we use a separate one and map.    //    //  DON'T mix the new and old methods!!    //    const XMLScanner::ValSchemes scheme = fScanner->getValidationScheme();    if (scheme == XMLScanner::Val_Always)        return true;    return false;}void DOMParser::setDoValidation(const bool newState){    fScanner->setDoValidation    (        newState ? XMLScanner::Val_Always : XMLScanner::Val_Never    );}//doctypehandler interfacesvoid DOMParser::attDef(    const   DTDElementDecl&     elemDecl    , const DTDAttDef&          attDef    , const bool                ignoring	){	    if (fDocumentType->isIntSubsetReading())    {        DOMString attString;        if (elemDecl.hasAttDefs())        {            attString.appendData(chOpenAngle);            attString.appendData(chBang);            attString.appendData(XMLUni::fgAttListString);            attString.appendData(chSpace);            attString.appendData(elemDecl.getFullName());            attString.appendData(chSpace);            attString.appendData(attDef.getFullName());            // Get the type and display it            const XMLAttDef::AttTypes type = attDef.getType();            switch(type)            {            case XMLAttDef::CData :                attString.appendData(chSpace);                attString.appendData(XMLUni::fgCDATAString);                break;            case XMLAttDef::ID :                attString.appendData(chSpace);                attString.appendData(XMLUni::fgIDString);                break;            case XMLAttDef::IDRef :                attString.appendData(chSpace);                attString.appendData(XMLUni::fgIDRefString);                break;            case XMLAttDef::IDRefs :                attString.appendData(chSpace);                attString.appendData(XMLUni::fgIDRefsString);                break;            case XMLAttDef::Entity :                attString.appendData(chSpace);                attString.appendData(XMLUni::fgEntityString);                break;            case XMLAttDef::Entities :

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?