void SYSTEM::CXMLConfiguration::Parse(std::string xmlcontent) { // ÅäÖýâÎö¹æÔò static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull }; impl = DOMImplementationRegistry::getDOMImplementation(gLS); if(!impl) return; // throw CException(GET_TEXT(ERR_XML_DOM_IMPLEMENTATION)); if(parser == NULL) parser = new XercesDOMParser; XercesDOMParser* xmlparser = (XercesDOMParser*)parser; xmlparser->setValidationScheme(XercesDOMParser::Val_Never); xmlparser->setLoadExternalDTD(false); xmlparser->setDoNamespaces(false); xmlparser->setDoSchema(false); xmlparser->setValidationSchemaFullChecking(false); xmlparser->setCreateEntityReferenceNodes(false); xmlparser->setIncludeIgnorableWhitespace(false); xmlparser->resetDocumentPool(); //ÖØÖÃÎĵµ»º³å³Ø MemBufInputSource input((XMLByte*) xmlcontent.c_str(), xmlcontent.size(), "memory"); xmlparser->parse(input); doc = xmlparser->getDocument(); if(doc) itemElement = ((XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument*)doc)->getDocumentElement(); //¸³Óè¸ù½Úµã else return; // throw CException(boost::str(boost::format(GET_TEXT(ERR_PARSE_CONFIG_FILE)) % xmlcontent)); }
bool XMLSceneryReader::openFile(const char* fileName) { bool result = false; XercesDOMParser* parser = new XercesDOMParser; parser->setValidationScheme(XercesDOMParser::Val_Never); parser->setDoSchema(false); parser->setLoadExternalDTD(false); parser->setErrorHandler(new XMLSceneryErrorHandler); parser->parse(LocalFileInputSource(XMLString::transcode(fileName))); if(!parser->getErrorCount()) { m_root = parser->getDocument()->getFirstChild(); m_node = m_root; result = true; } return result; }
bool SYSTEM::CXMLConfiguration::Open(std::string xmlpath) { // ÅäÖýâÎö¹æÔò static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull }; impl = DOMImplementationRegistry::getDOMImplementation(gLS); if(!impl) return false; // throw CException(GET_TEXT(ERR_XML_DOM_IMPLEMENTATION)); if(parser == NULL) parser = new XercesDOMParser; XercesDOMParser* xmlparser = (XercesDOMParser*)parser; xmlparser->setValidationScheme(XercesDOMParser::Val_Never); xmlparser->setDoNamespaces(false); xmlparser->setDoSchema(false); xmlparser->setValidationSchemaFullChecking(false); xmlparser->setCreateEntityReferenceNodes(false); xmlparser->setIncludeIgnorableWhitespace(false); xmlparser->resetDocumentPool(); //ÖØÖÃÎĵµ»º³å³Ø xmlparser->parse(xmlpath.c_str()); doc = xmlparser->getDocument(); if(doc) itemElement = ((XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument*)doc)->getDocumentElement(); //¸³Óè¸ù½Úµã else return false; //throw CException(boost::str(boost::format(GET_TEXT(ERR_PARSE_CONFIG_FILE)) % xmlpath)); xmlFile = xmlpath; return true; }
static void xsdproc (std::string const &schemadir, std::string const &input, std::string const &output) { XercesDOMParser parser; parser.setExternalSchemaLocation (( "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul " + schemadir + "/xul.xsd " "http://www.w3.org/1999/xhtml " + schemadir + "/xul-html.xsd " "http://www.w3.org/2000/10/xlink-ns " + schemadir + "/xml/xlink.xsd " //"http://www.w3.org/2001/SMIL20/ " + schemadir + "/smil/smil20.xsd " "http://www.w3.org/2001/XInclude " + schemadir + "/xml/xinclude.xsd " "http://www.w3.org/2002/07/owl# " + schemadir + "/owl/owl.xsd " "http://www.w3.org/XML/1998/namespace " + schemadir + "/xml/xml.xsd " ).c_str ()); parser.setCreateEntityReferenceNodes (true); parser.setDoNamespaces (true); parser.setDoSchema (true); parser.setDoXInclude (true); parser.setHandleMultipleImports (true); parser.setValidationSchemaFullChecking (true); parser.setValidationScheme (XercesDOMParser::Val_Always); error_handler handler; parser.setErrorHandler (&handler); parser.parse (input.c_str ()); if (handler.failed) throw std::runtime_error ("validation failed for " + input); serialise (parser.getDocument (), output); }
// --------------------------------------------------------------------------- // DOM Parser // --------------------------------------------------------------------------- int TestInit4DOM(const char* xmlFile, bool gDoNamespaces, bool gDoSchema, bool gSchemaFullChecking, Teststate theState) { TESTINITPRE; XercesDOMParser* parser = new XercesDOMParser; parser->setDoNamespaces(gDoNamespaces); parser->setDoSchema(gDoSchema); parser->setValidationSchemaFullChecking(gSchemaFullChecking); TESTINITPOST; }
// 解析TMS返回xml bool CTMSSensor::ParseXmlFromTMS(std::string &retXml,int &nRet) { XercesDOMParser *ptrParser = new XercesDOMParser; ptrParser->setValidationScheme( XercesDOMParser::Val_Never ); ptrParser->setDoNamespaces( true ); ptrParser->setDoSchema( false ); ptrParser->setLoadExternalDTD( false ); InputSource* ptrInputsource = new MemBufInputSource((XMLByte*)retXml.c_str(), retXml.size(), "bufId"); try { ptrParser->parse(*ptrInputsource); DOMDocument* ptrDoc = ptrParser->getDocument(); // 读取ret节点 DOMNodeList *ptrNodeList = ptrDoc->getElementsByTagName(C2X("ret")); if(ptrNodeList == NULL) { LOGIDFMT(ULOG_ERROR,ERROR_PARSE_MONITORSTATE_XML,"ParseXmlFromTMS:ret"); return false; } else { if(ptrNodeList->getLength() == 0) { LOGIDFMT(ULOG_ERROR,ERROR_PARSE_MONITORSTATE_XML,"ParseXmlFromTMS:ret"); return false; } DOMNode* ptrNode = ptrNodeList->item(0); char* pstate = XMLString::transcode(ptrNode->getFirstChild()->getNodeValue()); std::string str_state = pstate; if(!str_state.empty()) { nRet = atoi(str_state.c_str()); } XMLString::release(&pstate); //LOGINFFMT("%s,%s\n",str_name.c_str(),str_state.c_str()); } } catch( XMLException& e ) { char* message = XMLString::transcode( e.getMessage() ); XMLString::release( &message ); LOGIDFMT(ULOG_ERROR,ERROR_PARSE_MONITORSTATE_XML,message); delete ptrParser; ptrInputsource = NULL; delete ptrInputsource; ptrParser = NULL; } delete ptrParser; delete ptrInputsource; ptrInputsource = NULL; ptrParser = NULL; return true; }
void XMLRuntime::read(const string& filename, FreeAX25::Runtime::Configuration& config) { XercesDOMParser parser; parser.setValidationScheme(XercesDOMParser::Val_Always); parser.setDoNamespaces(true); parser.setDoSchema(true); parser.setDoXInclude(true); parser.setHandleMultipleImports(true); parser.setValidationSchemaFullChecking(true); parser.setCreateEntityReferenceNodes(false); parser.setIncludeIgnorableWhitespace(false); DOMTreeErrorReporter errReporter; parser.setErrorHandler(&errReporter); parser.parse(filename.c_str()); if (errReporter.getSawErrors()) throw exception(); // Now read configuration from the DOM Tree: XERCES_CPP_NAMESPACE::DOMDocument* doc = parser.getDocument(); assert(doc != nullptr); auto rootElement = doc->getDocumentElement(); auto configName = rootElement->getAttribute(toX("name")); config.setId(fmX(configName)); { // Get settings: auto nodeList = rootElement->getElementsByTagName(toX("Settings")); if (nodeList->getLength() > 0) readSettings( "", static_cast<DOMElement*>(nodeList->item(0)), config.settings); } { // Get plugins: auto nodeList = rootElement->getElementsByTagName(toX("Plugins")); if (nodeList->getLength() > 0) readPlugins( "", static_cast<DOMElement*>(nodeList->item(0)), config.plugins); } }
int myEppParser (char* xsdPath, char* xmlPath) { XMLPlatformUtils::Initialize(); // Initialize Xerces infrastructure XercesDOMParser parser; ParserErrorHandler parserErrorHandler; parser.setErrorHandler(&parserErrorHandler); // Enable schema processing. parser.setDoSchema(xsdValidationOn); // parser.setErrorHandler(&parserErrorHandler); parser.setValidationScheme(XercesDOMParser::Val_Auto); parser.setDoNamespaces(namespaceParsing); parser.cacheGrammarFromParse(true); // Let's preparse the schema grammar (.xsd) and cache it. loadXSD(xsdPath, &parser); validateXMLs(xmlPath, &parser); return 0; }
bool ColladaFile::Load(LPCWSTR lpszFileName) { if( PathFileExists( lpszFileName ) == FALSE ) { std::wstring strMessage; strMessage = strMessage + L"Colladaファイル[" + lpszFileName + L"]が見つかりませんでした"; MessageBox( NULL, strMessage.c_str(), L"ColladaFile::Load()", MB_OK | MB_ICONERROR ); return false; } XercesDOMParser* domParser = new XercesDOMParser(); domParser->setValidationScheme( AbstractDOMParser::Val_Auto ); // 構文が特殊な場合にのみ報告する domParser->setDoNamespaces( false ); // 名前空間処理はしない domParser->setDoSchema( false ); // スキーマ処理はしない domParser->setValidationSchemaFullChecking( false ); // 完全な構文のチェックはしない DomErrorReporter* errorHandler = new DomErrorReporter(); domParser->setErrorHandler( errorHandler ); bool bException = false; try { domParser->parse( (const XMLCh*)lpszFileName ); } catch( const OutOfMemoryException& ) { MessageBox( NULL, L"XMLファイルを処理中にメモリが不足しました", L"ColladaFile::Load()-OutOfMemoryException", MB_OK | MB_ICONERROR ); bException = false; } catch( const XMLException& ex ) { std::wstring strMessage = L"XMLファイルを処理中にエラーが発生しました\n\n"; strMessage += (const wchar_t*)ex.getMessage(); MessageBox( NULL, strMessage.c_str(), L"ColladaFile::Load()-XMLException", MB_OK | MB_ICONERROR ); bException = false; } catch( const DOMException& ex ) { std::wstring strMessage = L"XMLファイルを処理中にエラーが発生しました\n\n"; XMLCh temp[2048]; DOMImplementation::loadDOMExceptionMsg( ex.code, temp, 2047 ); strMessage += StrX( temp ).getStr(); MessageBox( NULL, strMessage.c_str(), L"ColladaFile::Load()-DOMException", MB_OK | MB_ICONERROR ); bException = false; } catch( ... ) { MessageBox( NULL, L"XMLファイルを処理中にエラーが発生しました", L"ColladaFile::Load()", MB_OK | MB_ICONERROR ); bException = false; } bool bError = bException || errorHandler->HasError(); if( bError == false ) // エラーが発生しなかった場合はドキュメントを処理する { CreateColladaObject( dynamic_cast<DOMNode*>(domParser->getDocument()) ); if( colladaObject->ValidElements() == false ) { std::wstring strMessage = L"読み込まれたCOLLADAファイルが不完全です\n\n"; strMessage += colladaObject->GetErrorMessage(); MessageBox( NULL, strMessage.c_str(), L"COLLADAファイルの読み込み", MB_OK | MB_ICONWARNING ); bError = true; } } else { std::wstring strMessage; if( errorHandler->GetFatalErrorMessage().empty() == false ) { strMessage += L"致命的なエラー\n"; strMessage += errorHandler->GetFatalErrorMessage(); } if( errorHandler->GetErrorMessage().empty() == false ) { strMessage += L"エラー\n"; strMessage += errorHandler->GetErrorMessage(); } if( strMessage.empty() == false ) // エラーメッセージがある場合は表示する { MessageBox( NULL, strMessage.c_str(), L"ColladaFile::Load()", MB_OK | MB_ICONERROR ); } } delete errorHandler; delete domParser; return bError == false; }
// --------------------------------------------------------------------------- int main(int argc, const char** argv) { try { XMLPlatformUtils::Initialize(); } catch(const XMLException& e) { StrX tmp_e(e.getMessage()); cerr << "Xerces initialization error: " << tmp_e.localForm() << endl; return 2; } // check command line for arguments if ( argc < 1 ) { cerr << "usage: schema-check <xml-file> [<schema-file> ...]" << endl; return 3; } XercesDOMParser *parser = new XercesDOMParser; DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter(); parser->setErrorHandler(errReporter); parser->setDoNamespaces(true); parser->setCreateEntityReferenceNodes(true); parser->useCachedGrammarInParse(true); if ( argc > 2 ) { parser->setDoSchema(true); parser->setDoValidation(true); parser->setValidationSchemaFullChecking(true); for ( int i = 2; i < argc; i++ ) { if ( parser->loadGrammar(argv[i], Grammar::SchemaGrammarType, true) == 0 ) { cerr << "Error loading grammar " << std::string(argv[i]) << endl; return 4; } } } bool errorsOccured = true; try { parser->parse(argv[1]); errorsOccured = false; } catch ( const OutOfMemoryException& ) { cerr << "Out of memory exception." << endl; } catch ( const XMLException& e ) { cerr << "An error occurred during parsing" << endl << " Message: " << StrX(e.getMessage()) << endl; } catch ( const DOMException& e ) { const unsigned int maxChars = 2047; XMLCh errText[maxChars + 1]; cerr << endl << "DOM Error during parsing: '" << std::string(argv[1]) << "'" << endl << "DOM Exception code is: " << e.code << endl; if ( DOMImplementation::loadDOMExceptionMsg(e.code, errText, maxChars) ) cerr << "Message is: " << StrX(errText) << endl; } catch (...) { cerr << "An error occurred during parsing." << endl; } return errorsOccured ? 1 : 0; }
// --------------------------------------------------------------------------- // // main // // --------------------------------------------------------------------------- int main(int argC, char* argV[]) { int retval = 0; // Initialize the XML4C2 system try { XMLPlatformUtils::Initialize(); } catch(const XMLException &toCatch) { XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n" << " Exception message:" << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl; return 1; } // Check command line and extract arguments. if (argC < 2) { usage(); XMLPlatformUtils::Terminate(); return 1; } // See if non validating dom parser configuration is requested. int parmInd; for (parmInd = 1; parmInd < argC; parmInd++) { // Break out on first parm not starting with a dash if (argV[parmInd][0] != '-') break; // Watch for special case help request if (!strcmp(argV[parmInd], "-?")) { usage(); XMLPlatformUtils::Terminate(); return 2; } else if (!strncmp(argV[parmInd], "-v=", 3) || !strncmp(argV[parmInd], "-V=", 3)) { const char* const parm = &argV[parmInd][3]; if (!strcmp(parm, "never")) gValScheme = XercesDOMParser::Val_Never; else if (!strcmp(parm, "auto")) gValScheme = XercesDOMParser::Val_Auto; else if (!strcmp(parm, "always")) gValScheme = XercesDOMParser::Val_Always; else { XERCES_STD_QUALIFIER cerr << "Unknown -v= value: " << parm << XERCES_STD_QUALIFIER endl; XMLPlatformUtils::Terminate(); return 2; } } else if (!strcmp(argV[parmInd], "-n") || !strcmp(argV[parmInd], "-N")) { gDoNamespaces = true; } else if (!strcmp(argV[parmInd], "-s") || !strcmp(argV[parmInd], "-S")) { gDoSchema = true; } else if (!strcmp(argV[parmInd], "-f") || !strcmp(argV[parmInd], "-F")) { gSchemaFullChecking = true; } else if (!strcmp(argV[parmInd], "-e") || !strcmp(argV[parmInd], "-E")) { gDoCreate = true; } else if (!strncmp(argV[parmInd], "-wenc=", 6)) { // Get out the encoding name gOutputEncoding = XMLString::transcode( &(argV[parmInd][6]) ); } else if (!strncmp(argV[parmInd], "-wfile=", 7)) { goutputfile = &(argV[parmInd][7]); } else if (!strncmp(argV[parmInd], "-wddc=", 6)) { const char* const parm = &argV[parmInd][6]; if (!strcmp(parm, "on")) gDiscardDefaultContent = true; else if (!strcmp(parm, "off")) gDiscardDefaultContent = false; else { XERCES_STD_QUALIFIER cerr << "Unknown -wddc= value: " << parm << XERCES_STD_QUALIFIER endl; XMLPlatformUtils::Terminate(); return 2; } } else if (!strncmp(argV[parmInd], "-wscs=", 6)) { const char* const parm = &argV[parmInd][6]; if (!strcmp(parm, "on")) gSplitCdataSections = true; else if (!strcmp(parm, "off")) gSplitCdataSections = false; else { XERCES_STD_QUALIFIER cerr << "Unknown -wscs= value: " << parm << XERCES_STD_QUALIFIER endl; XMLPlatformUtils::Terminate(); return 2; } } else if (!strncmp(argV[parmInd], "-wflt=", 6)) { const char* const parm = &argV[parmInd][6]; if (!strcmp(parm, "on")) gUseFilter = true; else if (!strcmp(parm, "off")) gUseFilter = false; else { XERCES_STD_QUALIFIER cerr << "Unknown -wflt= value: " << parm << XERCES_STD_QUALIFIER endl; XMLPlatformUtils::Terminate(); return 2; } } else if (!strncmp(argV[parmInd], "-wfpp=", 6)) { const char* const parm = &argV[parmInd][6]; if (!strcmp(parm, "on")) gFormatPrettyPrint = true; else if (!strcmp(parm, "off")) gFormatPrettyPrint = false; else { XERCES_STD_QUALIFIER cerr << "Unknown -wfpp= value: " << parm << XERCES_STD_QUALIFIER endl; XMLPlatformUtils::Terminate(); return 2; } } else if (!strncmp(argV[parmInd], "-wbom=", 6)) { const char* const parm = &argV[parmInd][6]; if (!strcmp(parm, "on")) gWriteBOM = true; else if (!strcmp(parm, "off")) gWriteBOM = false; else { XERCES_STD_QUALIFIER cerr << "Unknown -wbom= value: " << parm << XERCES_STD_QUALIFIER endl; XMLPlatformUtils::Terminate(); return 2; } } else { XERCES_STD_QUALIFIER cerr << "Unknown option '" << argV[parmInd] << "', ignoring it.\n" << XERCES_STD_QUALIFIER endl; } } // // And now we have to have only one parameter left and it must be // the file name. // if (parmInd + 1 != argC) { usage(); XMLPlatformUtils::Terminate(); return 1; } gXmlFile = argV[parmInd]; // // Create our parser, then attach an error handler to the parser. // The parser will call back to methods of the ErrorHandler if it // discovers errors during the course of parsing the XML document. // XercesDOMParser *parser = new XercesDOMParser; parser->setValidationScheme(gValScheme); parser->setDoNamespaces(gDoNamespaces); parser->setDoSchema(gDoSchema); parser->setValidationSchemaFullChecking(gSchemaFullChecking); parser->setCreateEntityReferenceNodes(gDoCreate); DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter(); parser->setErrorHandler(errReporter); // // Parse the XML file, catching any XML exceptions that might propogate // out of it. // bool errorsOccured = false; try { parser->parse(gXmlFile); } catch (const OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl; errorsOccured = true; } catch (const XMLException& e) { XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n Message: " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl; errorsOccured = true; } catch (const DOMException& e) { const unsigned int maxChars = 2047; XMLCh errText[maxChars + 1]; XERCES_STD_QUALIFIER cerr << "\nDOM Error during parsing: '" << gXmlFile << "'\n" << "DOMException code is: " << e.code << XERCES_STD_QUALIFIER endl; if (DOMImplementation::loadDOMExceptionMsg(e.code, errText, maxChars)) XERCES_STD_QUALIFIER cerr << "Message is: " << StrX(errText) << XERCES_STD_QUALIFIER endl; errorsOccured = true; } catch (...) { XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n " << XERCES_STD_QUALIFIER endl; errorsOccured = true; } // If the parse was successful, output the document data from the DOM tree if (!errorsOccured && !errReporter->getSawErrors()) { DOMPrintFilter *myFilter = 0; try { // get a serializer, an instance of DOMWriter XMLCh tempStr[100]; XMLString::transcode("LS", tempStr, 99); DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr); DOMWriter *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter(); // set user specified output encoding theSerializer->setEncoding(gOutputEncoding); // plug in user's own filter if (gUseFilter) { // even we say to show attribute, but the DOMWriter // will not show attribute nodes to the filter as // the specs explicitly says that DOMWriter shall // NOT show attributes to DOMWriterFilter. // // so DOMNodeFilter::SHOW_ATTRIBUTE has no effect. // same DOMNodeFilter::SHOW_DOCUMENT_TYPE, no effect. // myFilter = new DOMPrintFilter(DOMNodeFilter::SHOW_ELEMENT | DOMNodeFilter::SHOW_ATTRIBUTE | DOMNodeFilter::SHOW_DOCUMENT_TYPE); theSerializer->setFilter(myFilter); } // plug in user's own error handler DOMErrorHandler *myErrorHandler = new DOMPrintErrorHandler(); theSerializer->setErrorHandler(myErrorHandler); // set feature if the serializer supports the feature/mode if (theSerializer->canSetFeature(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections)) theSerializer->setFeature(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections); if (theSerializer->canSetFeature(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent)) theSerializer->setFeature(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent); if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint)) theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint); if (theSerializer->canSetFeature(XMLUni::fgDOMWRTBOM, gWriteBOM)) theSerializer->setFeature(XMLUni::fgDOMWRTBOM, gWriteBOM); // // Plug in a format target to receive the resultant // XML stream from the serializer. // // StdOutFormatTarget prints the resultant XML stream // to stdout once it receives any thing from the serializer. // XMLFormatTarget *myFormTarget; if (goutputfile) myFormTarget = new LocalFileFormatTarget(goutputfile); else myFormTarget = new StdOutFormatTarget(); // get the DOM representation DOMNode *doc = parser->getDocument(); // // do the serialization through DOMWriter::writeNode(); // theSerializer->writeNode(myFormTarget, *doc); delete theSerializer; // // Filter, formatTarget and error handler // are NOT owned by the serializer. // delete myFormTarget; delete myErrorHandler; if (gUseFilter) delete myFilter; } catch (const OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl; retval = 5; } catch (XMLException& e) { XERCES_STD_QUALIFIER cerr << "An error occurred during creation of output transcoder. Msg is:" << XERCES_STD_QUALIFIER endl << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl; retval = 4; } } else retval = 4; // // Clean up the error handler. The parser does not adopt handlers // since they could be many objects or one object installed for multiple // handlers. // delete errReporter; // // Delete the parser itself. Must be done prior to calling Terminate, below. // delete parser; // And call the termination method XMLPlatformUtils::Terminate(); XMLString::release(&gOutputEncoding); return retval; }
//initialize a ResultXML object using an existing xml file ResultXML::ResultXML(const char *file) { //sets-up for XML processing and handle any errors if unsuccessful try{ XMLPlatformUtils::Initialize(); } catch (XMLException &e){ char *msg = XMLString::transcode(e.getMessage()); XERCES_STD_QUALIFIER cerr << "Error During Initialization: " << endl << msg; XMLString::release(&msg); } catch (...){ cerr << "Error Unknown Exception Encountered!" << endl; } //create a parser and set it to validate document but not load a DTD or use a schema XercesDOMParser *parser = new XercesDOMParser(); parser->setValidationScheme(XercesDOMParser::Val_Always); parser->setDoSchema(false); parser->setLoadExternalDTD(false); try{ //create unicode strings to for later use XMLCh *spdName = XMLString::transcode("speed_result"); XMLCh *memName = XMLString::transcode("memory_result"); XMLCh *sectName = XMLString::transcode("section_list"); XMLCh *fname = XMLString::transcode(file); //set the save location, parse the file and retrieve the required nodes ftarget = new LocalFileFormatTarget(fname); parser->parse(file); doc = parser->getDocument(); root = doc->getDocumentElement(); DOMNodeList *nlist = root->getChildNodes(); //go through the nodelist finding the top level child nodes and assign them to the right member variables for(XMLSize_t i=0; i<nlist->getLength(); i++){ DOMNode *curNode = nlist->item(i); DOMElement *curElm; //safely check for element node before casting if(curNode->getNodeType() == DOMNode::ELEMENT_NODE){ curElm = dynamic_cast<DOMElement*>(curNode); } //check the tag name and assign accordingly if(XMLString::equals(spdName, curElm->getTagName())){ spdResult = curElm; } else if(XMLString::equals(memName, curElm->getTagName())){ memResult = curElm; } else if(XMLString::equals(sectName, curElm->getTagName())){ sectList = curElm; } } //release the memory occupied by the encoded strings XMLString::release(&spdName); XMLString::release(&memName); XMLString::release(§Name); XMLString::release(&fname); } catch (const OutOfMemoryException&){ XERCES_STD_QUALIFIER cerr << "Error Out of Memory Exception: " << XERCES_STD_QUALIFIER endl; } catch (const DOMException& e){ XERCES_STD_QUALIFIER cerr << "Error DOMException Encountered Code: " << e.code << XERCES_STD_QUALIFIER endl; } catch (...){ XERCES_STD_QUALIFIER cerr << "Unknown Error Encountered, Could Not Create Document" << XERCES_STD_QUALIFIER endl; } delete parser; }
XERCES_CPP_NAMESPACE_USE int main( int argc, char *argv[] ) { std::cout << "****************************" << std::endl; std::cout << "XML DOM PARSER PLAY" << std::endl; std::cout << "****************************" << std::endl; try { XMLPlatformUtils::Initialize(); } catch( const XMLException& ex ) { std::cerr << "error with xml initialisation:" << ex.getMessage() << std::endl; return 1; } std::cout << "Building parser ..." << std::endl; XercesDOMParser* parser = new XercesDOMParser(); if( !parser ) { std::cerr << "no parser" << std::endl; return 1; } parser->setValidationScheme(XercesDOMParser::Val_Always); parser->setDoNamespaces(false); parser->setDoSchema(false); parser->setCreateEntityReferenceNodes(false); std::cout << "Building error handler" << std::endl; ErrorHandler* errHandler = dynamic_cast<ErrorHandler*>(new HandlerBase()); if( errHandler == 0 ) { std::cerr << "ibad cast" << std::endl; return 1; } if( errHandler == 0 ) { std::cerr << "error with errorhandler caszting:" << std::endl; return 1; } parser->setErrorHandler(errHandler); char* xmlFile = "/home/suggitpe/test/RPMS/config/rpms_config.xml"; try { parser->parse(xmlFile); if( parser->getErrorCount() == 0 ) { std::cerr << "errors in parsing" << std::endl; return 1; } DOMDocument * doc = parser->getDocument(); if( doc->hasChildNodes() ) { std::cout << "Num nodes: " << doc->getChildNodes()->getLength() << std::endl; for( int i = 0; i < doc->getChildNodes()->getLength();++i ) { cout << "\t" << i << " type: " << doc->getChildNodes()->item(i)->getNodeType() << endl; if( doc->getChildNodes()->item(i)->getNodeType() == 1 ) { DOMElement *e = dynamic_cast<DOMElement*>(doc->getChildNodes()->item(i)); if( !e ) { cerr << "bad cast" << endl; } if( e->hasChildNodes() ) { cout << "\t\telement found with " << e->getChildNodes()->getLength() << " nodes"<< endl; } else { cout << "No child nodes" << endl; } } } cout << "now for the other way" << endl; XMLCh * name = XMLString::transcode("system_components"); DOMNodeList *list = doc->getDocumentElement()->getElementsByTagName( name ); XMLString::release(&name); std::cout << "Got list [" << list->getLength() << "]" << std::endl; for( XMLSize_t i =0; i < list->getLength(); ++i ) { std::cout << "." << std::endl; } } else { std::cout << "no child nodes" << std::endl; } } catch( const XMLException& ex ) { std::cerr << "error with xml parser:" << ex.getMessage() << std::endl; return 1; } catch( const DOMException& dex ) { std::cerr << "error with xml parser:" << dex.msg << std::endl; return 1; } catch(...) { std::cerr << "unknown problems" << std::endl; return 1; } delete parser; delete errHandler; std::cout << "****************************" << std::endl; std::cout << "" << std::endl; return 0; }
int ParameterManager::LoadDocument(const XERCES_CPP_NAMESPACE_QUALIFIER InputSource& inputSource) { // // Create our parser, then attach an error handler to the parser. // The parser will call back to methods of the ErrorHandler if it // discovers errors during the course of parsing the XML document. // XercesDOMParser *parser = new XercesDOMParser; parser->setValidationScheme(gValScheme); parser->setDoNamespaces(gDoNamespaces); parser->setDoSchema(gDoSchema); parser->setValidationSchemaFullChecking(gSchemaFullChecking); parser->setCreateEntityReferenceNodes(gDoCreate); DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter(); parser->setErrorHandler(errReporter); // // Parse the XML file, catching any XML exceptions that might propagate // out of it. // bool errorsOccured = false; try { parser->parse(inputSource); } catch (const XMLException& e) { std::cerr << "An error occurred during parsing\n Message: " << StrX(e.getMessage()) << std::endl; errorsOccured = true; } catch (const DOMException& e) { std::cerr << "A DOM error occurred during parsing\n DOMException code: " << e.code << std::endl; errorsOccured = true; } catch (...) { std::cerr << "An error occurred during parsing\n " << std::endl; errorsOccured = true; } if (errorsOccured) { delete parser; delete errReporter; return 0; } _pDocument = parser->adoptDocument(); delete parser; delete errReporter; if (!_pDocument) throw XMLBaseException("Malformed Parameter document: Invalid document"); DOMElement* rootElem = _pDocument->getDocumentElement(); if (!rootElem) throw XMLBaseException("Malformed Parameter document: Root group not found"); _pGroupNode = FindElement(rootElem,"FCParamGroup","Root"); if (!_pGroupNode) throw XMLBaseException("Malformed Parameter document: Root group not found"); return 1; }
int parseTEI( const char* xmlFile, bool english, SentenceList& sentenceList ) { try { XMLPlatformUtils::Initialize(); } catch(const XMLException &toCatch) { std::cerr << "Error during Xerces-c Initialization.\n" << " Exception message:" << StrX(toCatch.getMessage()) << std::endl; return 1; } // // Create our parser, then attach an error handler to the parser. // The parser will call back to methods of the ErrorHandler if it // discovers errors during the course of parsing the XML document. // XercesDOMParser *parser = new XercesDOMParser; parser->setValidationScheme(XercesDOMParser::Val_Never); parser->setDoNamespaces(false); parser->setDoSchema(false); parser->setValidationSchemaFullChecking(false); parser->setCreateEntityReferenceNodes(false); DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter(); parser->setErrorHandler(errReporter); // // Parse the XML file, catching any XML exceptions that might propogate // out of it. // bool errorsOccured = false; try { parser->parse(xmlFile); } catch (const XMLException& e) { std::cerr << "An error occurred during parsing\n Message: " << StrX(e.getMessage()) << std::endl; errorsOccured = true; } catch (const DOMException& e) { const unsigned int maxChars = 2047; XMLCh errText[maxChars + 1]; std::cerr << "\nDOM Error during parsing: '" << xmlFile << "'\n" << "DOMException code is: " << e.code << std::endl; if (DOMImplementation::loadDOMExceptionMsg(e.code, errText, maxChars)) std::cerr << "Message is: " << StrX(errText) << std::endl; errorsOccured = true; } catch (...) { std::cerr << "An error occurred during parsing\n " << std::endl; errorsOccured = true; } if (errorsOccured || errReporter->getSawErrors()) return -1; // get the DOM representation DOMNode *doc = parser->getDocument(); sentenceList.clear(); buildSentenceListFromDOMTree(doc,sentenceList,english); delete errReporter; // Delete the parser itself. Must be done prior to calling Terminate, below. delete parser; // And call the termination method XMLPlatformUtils::Terminate(); return 0; }