static bool SAMLLoadSchema(XercesDOMParser &parser, const SAMLGlibString &schemaDir, const char *filename) { SAMLGlibString schemaPath(g_build_filename(schemaDir.c_str(), filename, NULL)); Grammar *g = parser.loadGrammar(schemaPath.c_str(), Grammar::SchemaGrammarType, true); if (g == NULL) { /* * The parser complains even with official schemas, so we don't * normally set an error handler. However, this should not fail since * we control these files, so try again with logging, so we can see * what went wrong. */ SAMLErrorHandler errorHandler; parser.setErrorHandler(&errorHandler); g = parser.loadGrammar(schemaPath.c_str(), Grammar::SchemaGrammarType, true); Warning("Failed to load XML Schema from %s.\n", schemaPath.c_str()); return false; } 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); }
void Parameters::readFile(string str){ file = str; XMLPlatformUtils::Initialize(); XercesDOMParser parser; parser.setValidationScheme(XercesDOMParser::Val_Always); HandlerBase errHandler;// = (ErrorHandler*) new HandlerBase(); parser.setErrorHandler(&errHandler); parser.parse(str.c_str()); DOMDocument * doc = parser.getDocument(); DOMElement* elementRoot = doc->getDocumentElement(); // Extract floats DOMElement* floatRoot = (DOMElement *) elementRoot->getElementsByTagName(XMLString::transcode("real"))->item(0); DOMElement* child = floatRoot->getFirstElementChild(); do{ saveReal(XMLString::transcode(child->getNodeName()), atof(XMLString::transcode(child->getTextContent()))); child = child->getNextElementSibling(); }while(child != NULL); // Extract integers DOMElement* intRoot = (DOMElement *) elementRoot->getElementsByTagName(XMLString::transcode("integer"))->item(0); child = intRoot->getFirstElementChild(); do{ saveInteger( XMLString::transcode(child->getNodeName()), atoi(XMLString::transcode(child->getTextContent()))); child = child->getNextElementSibling(); }while(child != NULL); }
map<string, DatasetSpecification> Specifications::readDatasetIndex(string str){ map<string, DatasetSpecification> result; XERCES_CPP_NAMESPACE_USE XMLPlatformUtils::Initialize(); XercesDOMParser parser; parser.setValidationScheme(XercesDOMParser::Val_Always); HandlerBase errHandler;// = (ErrorHandler*) new HandlerBase(); parser.setErrorHandler(&errHandler); parser.parse(str.c_str()); DOMDocument * doc = parser.getDocument(); DOMElement* elementRoot = doc->getDocumentElement(); DOMNodeList *entries = elementRoot->getElementsByTagName(XMLString::transcode("dataset")); cout << "Databases in index:\n"; for(size_t i = 0; i < entries->getLength(); ++i){ DOMNode *current = entries->item(i); DatasetSpecification dss; dss.name = XMLString::transcode(current->getAttributes()-> getNamedItem(XMLString::transcode("name"))-> getNodeValue()); dss.root = XMLString::transcode(current->getAttributes()-> getNamedItem(XMLString::transcode("root"))-> getNodeValue()); cout << " name: " << dss.name << " root: " << dss.root << endl; DOMNodeList *categories = current->getChildNodes(); for(size_t j = 0; j < categories->getLength(); ++j) if((string) XMLString::transcode(categories->item(j)->getNodeName()) == "category") dss.categories.push_back(XMLString::transcode(categories->item(j)->getTextContent())); result[dss.name] = dss; } return result; }
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; }
void Generation::readGenerations(const string &file, vector<GenerationPtr> &generations) { XMLPlatformUtils::Initialize(); XercesDOMParser parser; GenerationErrorHandler handler; parser.setErrorHandler(&handler); parser.setEntityResolver(&handler); parser.parse(file.c_str()); DOMDocument *doc = parser.getDocument(); DOMElement *root = doc->getDocumentElement(); XMLCh tempStr[12]; XMLString::transcode("generation", tempStr, 11); DOMNodeList *list = root->getElementsByTagName(tempStr); int length = list->getLength(); for (int i = 0; i < length; ++i) { DOMElement *item = (DOMElement *)list->item(i); GenerationPtr generation(new Generation()); generation->m_impl->m_owner = generation.get(); generation->m_impl->getGeneration(item); generation->m_impl->m_idx = i; generations.push_back(generation); } }
Parser* parseHTML(std::string contents) { try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { char* msg = XMLString::transcode(toCatch.getMessage()); cout << "INIT_ERR:" << endl; cout << msg << endl; XMLString::release(&msg); return NULL; } XercesDOMParser* parser = new XercesDOMParser(); parser->setValidationScheme(XercesDOMParser::Val_Always); parser->setDoNamespaces(true); ErrorHandler* err = (ErrorHandler*) new HandlerBase(); parser->setErrorHandler(err); try { MemBufInputSource xml((const XMLByte*)contents.c_str(), contents.size(), "html", false); parser->parse(xml); parser->adoptDocument(); delete parser; delete err; XMLPlatformUtils::Terminate(); return parser; } catch (const XMLException &toCatch) { char* msg = XMLString::transcode(toCatch.getMessage()); cout << "XML_ERR: "; cout << msg << endl; XMLString::release(&msg); return parser; } catch (const DOMException &toCatch) { char* msg = XMLString::transcode(toCatch.getMessage()); cout << "DOM_ERR: "; cout << msg << endl; XMLString::release(&msg); return parser; } catch (const SAXException &toCatch) { char* msg = XMLString::transcode(toCatch.getMessage()); cout << "SAX_ERR: "; cout << msg << endl; XMLString::release(&msg); return parser; } catch (...) { cout << "!UNKNOWN_ERR!" << endl; return parser; } delete parser; delete err; XMLPlatformUtils::Terminate(); return NULL; }
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; }
DOMDocument* tsp::Tool::parserXml(string myxml) { if (!initXmlEngine() || myxml.empty()) return NULL; XercesDOMParser* parser = new XercesDOMParser(); parser->setValidationScheme(XercesDOMParser::Val_Always); parser->setDoNamespaces(true); // optional ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase(); parser->setErrorHandler(errHandler); try { MemBufInputSource src((const XMLByte*) myxml.c_str(), myxml.length(), "dummy", false); parser->parse(src); } catch (const XMLException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); cout << "Exception message is: \n" << message << "\n"; XMLString::release(&message); return NULL; } catch (const DOMException& toCatch) { char* message = XMLString::transcode(toCatch.msg); cout << "Exception message is: \n" << message << "\n"; XMLString::release(&message); return NULL; } catch (...) { cout << "Unexpected Exception \n"; return NULL; } DOMDocument* doc; doc = parser->getDocument(); delete errHandler; return doc; }
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; }
bool XmlWorldParser::process_xml(const char* xmlFile) { try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); cout << "Error during initialization! :\n" << message << "\n"; XMLString::release(&message); return 1; } XercesDOMParser* parser = new XercesDOMParser(); parser->setValidationScheme(XercesDOMParser::Val_Always); parser->setDoNamespaces(true); // optional /** * Configure parser error handling */ ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase(); // ErrorHandler *errHandler =(ErrorHandler*) new DOMPrintErrorHandler(); parser->setErrorHandler(errHandler); try { parser->parse(xmlFile); } catch (const XMLException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); cout << "Exception message is: \n" << message << "\n"; XMLString::release(&message); return -1; } catch (const DOMException& toCatch) { char* message = XMLString::transcode(toCatch.msg); cout << "Exception message is: \n" << message << "\n"; XMLString::release(&message); return -1; } catch (const SAXException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); cout << "Exception message is: " << message << "\n"; XMLString::release(&message); return -1; } catch (const exception& toCatch) { cout << "Unexpected Exception \n" << toCatch.what() << endl; return -1; } /** * Walk through the document, adding bodies and joints in their relative frames */ DOMDocument* doc = parser->getDocument(); DOMTreeWalker* walker = doc->createTreeWalker(doc->getDocumentElement(), DOMNodeFilter::SHOW_ELEMENT, new BodiesInWorld(), true); /** Initial world frame */ double transform[3] = { 0, 0, 0 }; processNode(walker, transform); //TODO Ensure that I am cleaning up everything I need to /** Clean up no longer needed resources **/ doc->release(); delete errHandler; return true; }
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; }
/* Method to call to initisalize the parsing */ int XMLData::parseXML(string filePath) { try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); cout << "Error during initialization! :\n" << message << "\n"; XMLString::release(&message); return 1; } XercesDOMParser* parser = new XercesDOMParser(); parser->setValidationScheme(XercesDOMParser::Val_Always); parser->setDoNamespaces(true); ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase(); parser->setErrorHandler(errHandler); try { parser->parse(filePath.c_str()); DOMDocument* dom = parser->getDocument(); XMLData::parseDOMNode(dom); } catch (const XMLException& e) { char* message = XMLString::transcode(e.getMessage()); cout << "XMLException is: \n\t" << message << "\n"; XMLString::release(&message); return 2; } catch (const DOMException& e) { char* message = XMLString::transcode(e.msg); cout << "DOMException is: \n\t" << message << "\n"; XMLString::release(&message); return 3; } catch (const SAXException& e) { char* message = XMLString::transcode(e.getMessage()); cout << "SAXException is: \n\t" << message << "\n"; XMLString::release(&message); return 4; } catch (...) { cout << "Unexpected Exception \n"; return 5; } delete parser; delete errHandler; XMLPlatformUtils::Terminate(); if(hairTypeLength == -1) { hairTypeLength = nbBitsMin(hairTypes.size()-1); } if(limbTypeLength == -1) { limbTypeLength = nbBitsMin(limbTypes.size()-1); } if(mouthWidthTypeLength == -1) { mouthWidthTypeLength = nbBitsMin(mouthWidthTypes.size()-1); } if(teethTypeLength == -1) { teethTypeLength = nbBitsMin(teethTypes.size()-1); } return 0; }
//----------------------------------------------------------------------------- // Purpose: load up a project and parse it //----------------------------------------------------------------------------- bool CVCProjConvert::LoadProject( const char *project ) { #ifdef _WIN32 HRESULT hr; IXMLDOMDocument *pXMLDoc=NULL; hr = ::CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)&pXMLDoc); if (FAILED(hr)) { Msg ("Cannot instantiate msxml2.dll\n"); Msg ("Please download the MSXML run-time (url below)\n"); Msg ("http://msdn.microsoft.com/downloads/default.asp?url=/downloads/sample.asp?url=/msdn-files/027/001/766/msdncompositedoc.xml\n"); return false; } VARIANT_BOOL vtbool; _variant_t bstrProject(project); pXMLDoc->put_async( VARIANT_BOOL(FALSE) ); hr = pXMLDoc->load(bstrProject,&vtbool); if (FAILED(hr) || vtbool==VARIANT_FALSE) { Msg ("Could not open %s.\n", bstrProject); pXMLDoc->Release(); return false; } #elif _LINUX XercesDOMParser* parser = new XercesDOMParser(); parser->setValidationScheme(XercesDOMParser::Val_Always); // optional. parser->setDoNamespaces(true); // optional ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase(); parser->setErrorHandler(errHandler); try { parser->parse(project); } catch (const XMLException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); Error( "Exception message is: %s\n", message ); XMLString::release(&message); return; } catch (const DOMException& toCatch) { char* message = XMLString::transcode(toCatch.msg); Error( "Exception message is: %s\n", message ); XMLString::release(&message); return; } catch (...) { Error( "Unexpected Exception \n" ); return; } DOMDocument *pXMLDoc = parser->getDocument(); #endif ExtractProjectName( pXMLDoc ); if ( !m_Name.IsValid() ) { Msg( "Failed to extract project name\n" ); return false; } char baseDir[ MAX_PATH ]; Q_ExtractFilePath( project, baseDir, sizeof(baseDir) ); Q_StripTrailingSlash( baseDir ); m_BaseDir = baseDir; ExtractConfigurations( pXMLDoc ); if ( m_Configurations.Count() == 0 ) { Msg( "Failed to find any configurations to load\n" ); return false; } ExtractFiles( pXMLDoc ); #ifdef _WIN32 pXMLDoc->Release(); #elif _LINUX delete pXMLDoc; delete errHandler; #endif m_bProjectLoaded = true; return true; }
// --------------------------------------------------------------------------- // // 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; }
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 parse_header_config(char *filename,int is_credit) { int parse_status = 0 ; // if parse_status is non-zero , return FAILURE struct stat st; if(lstat(filename,&st) != 0) { emit_bypass(FILE_LINE,"configuration file %s doesn't exist,please check ENV HEADER_CONFIG_PATH is set",filename); return FAILURE; } DOMNodeList *nodeList = NULL; DOMNode *node = NULL; try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); emit_bypass(FILE_LINE, "Failed to process file %s", filename); emit_bypass(FILE_LINE, " Error during initialization %s",message); XMLString::release(&message); return FAILURE; } XercesDOMParser* parser = new XercesDOMParser(); parser->setValidationScheme(XercesDOMParser::Val_Always); parser->setDoNamespaces(true); ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase(); parser->setErrorHandler(errHandler); try { parser->parse(filename); DOMDocument *doc = parser->getDocument(); nodeList = doc->getElementsByTagName(XMLString::transcode("xmlns")); node = nodeList->item(0); if (!node) { emit_bypass(FILE_LINE,"xmlns is not found in configurtion file %s",filename); parse_status = 1; } if (parse_status !=1 ) { if(is_credit!=1) { strcpy(gXmlns_str,XMLString::transcode(node->getTextContent())); if (strlen(gXmlns_str) == 0) { emit_bypass(FILE_LINE,"xmlns is set empty in configurtion file %s",filename); parse_status = 1; } } else { strcpy(gXmlns_str_credit,XMLString::transcode(node->getTextContent())); if(strlen(gXmlns_str_credit) == 0) { emit_bypass(FILE_LINE,"xmlns is set empty in configurtion file %s",filename); parse_status = 1; } } } nodeList = doc->getElementsByTagName(XMLString::transcode("xsi")); node = nodeList->item(0); if (!node) { emit_bypass(FILE_LINE,"xsi is not found in configuration file %s",filename); parse_status = 2; } if (parse_status != 2) { if(is_credit!=1) { strcpy(gXsi_str,XMLString::transcode(node->getTextContent())); if (strlen(gXsi_str) == 0) { emit_bypass(FILE_LINE,"xsi is set empty in configurtion file %s",filename); parse_status = 2; } } else { strcpy(gXsi_str_credit,XMLString::transcode(node->getTextContent())); if (strlen(gXsi_str_credit) == 0) { emit_bypass(FILE_LINE,"xsi is set empty in configurtion file %s",filename); parse_status = 2; } } } nodeList = doc->getElementsByTagName(XMLString::transcode("schemaLocation")); node = nodeList->item(0); if (!node) { emit_bypass(FILE_LINE,"schemaLocation is not found in configuration file %s",filename); parse_status = 3; } if (parse_status !=3) { if(is_credit!=1) { strcpy(gSchemaLocation_str,XMLString::transcode(node->getTextContent())); if (strlen(gSchemaLocation_str) == 0) { emit_bypass(FILE_LINE," schemaLocation is set empty in configurtion file %s",filename); parse_status = 3; } } else { strcpy(gSchemaLocation_str_credit,XMLString::transcode(node->getTextContent())); if (strlen(gSchemaLocation_str_credit) == 0) { emit_bypass(FILE_LINE," schemaLocation is set empty in configurtion file %s",filename); parse_status = 3; } } } delete parser; delete errHandler; XMLPlatformUtils::Terminate(); if (parse_status != 0) return FAILURE; return SUCCESS; } catch (const DOMException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); emit_bypass(FILE_LINE, "Failed to process file %s", filename); emit_bypass(FILE_LINE, "Exception message is:%s", message); } catch (exception& e) { emit_bypass(FILE_LINE, "Failed to process file %s", filename); emit_bypass(FILE_LINE, "Exception message is:%s", e.what()); } catch (...){ emit_bypass(FILE_LINE, "Failed to process file %s", filename); } delete parser; delete errHandler; XMLPlatformUtils::Terminate(); return FAILURE; }
DOMDocument * XIncludeUtils::doXIncludeXMLFileDOM(const XMLCh *href, const XMLCh *relativeHref, DOMNode *includeNode, DOMDocument *parsedDocument, XMLEntityHandler* entityResolver){ if (XIncludeUtils::isInCurrentInclusionHistoryStack(href)){ /* including something back up the current history */ XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeCircularInclusionLoop, href, href); return NULL; } if (XMLString::equals(href, parsedDocument->getBaseURI())){ /* trying to include itself */ XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeCircularInclusionDocIncludesSelf, href, href); return NULL; } /* Instantiate the DOM parser. */ XercesDOMParser parser; parser.setDoNamespaces(true); /* don't want to recurse the xi processing here */ parser.setDoXInclude(false); /* create the schema info nodes, so that we can detect conflicting notations */ parser.setCreateSchemaInfo(true); XMLInternalErrorHandler xierrhandler; parser.setErrorHandler(&xierrhandler); DOMDocument *includedNode = NULL; try { InputSource* is=NULL; Janitor<InputSource> janIS(is); if(entityResolver) { XMLResourceIdentifier resIdentifier(XMLResourceIdentifier::ExternalEntity, relativeHref, NULL, NULL, includeNode->getBaseURI()); is=entityResolver->resolveEntity(&resIdentifier); janIS.reset(is); } if(janIS.get()!=NULL) parser.parse(*janIS.get()); else parser.parse(href); /* need to be able to release the parser but keep the document */ if (!xierrhandler.getSawError() && !xierrhandler.getSawFatal()) includedNode = parser.adoptDocument(); } catch (const XMLException& /*toCatch*/) { XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeResourceErrorWarning, href, href); } catch (const DOMException& /*toCatch*/) { XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeResourceErrorWarning, href, href); } catch (...) { XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeResourceErrorWarning, href, href); } //addDocumentURIToCurrentInclusionHistoryStack(href); if(includedNode != NULL){ /* baseURI fixups - see http://www.w3.org/TR/xinclude/#base for details. */ DOMElement *topLevelElement = includedNode->getDocumentElement(); if (topLevelElement && topLevelElement->getNodeType() == DOMNode::ELEMENT_NODE ){ XMLUri parentURI(includeNode->getBaseURI()); XMLUri includedURI(includedNode->getBaseURI()); /* if the paths differ we need to add a base attribute */ if (!XMLString::equals(parentURI.getPath(), includedURI.getPath())){ if (getBaseAttrValue(topLevelElement) == NULL){ /* need to calculate the proper path difference to get the relativePath */ topLevelElement->setAttribute(fgXIBaseAttrName, relativeHref); } else { /* the included node has base of its own which takes precedence */ XIncludeLocation xil(getBaseAttrValue(topLevelElement)); if (getBaseAttrValue(includeNode) != NULL){ /* prepend any specific base modification of the xinclude node */ xil.prependPath(getBaseAttrValue(includeNode)); } topLevelElement->setAttribute(fgXIBaseAttrName, xil.getLocation()); } } } } return includedNode; }
bool ServerConfigXMLReader::readServerConfig(const std::string & path) { this->serverConfig = ServerConfig(); try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { char * message = XMLString::transcode(toCatch.getMessage()); cout << "Error during initialization! :\n" << message << "\n"; XMLString::release(&message); return false; } XercesDOMParser * parser = new XercesDOMParser(); //parser->setValidationScheme(XercesDOMParser::Val_Auto); parser->setDoNamespaces(true); parser->setDoXInclude(true); //parser->setValidationScheme(XercesDOMParser::Val_Always); // parser->setDoSchema(true); // parser->setValidationSchemaFullChecking(true); XMLParseErrorReporter * xmlParseErrorReporter = new XMLParseErrorReporter();; parser->setErrorHandler(xmlParseErrorReporter); try { parser->parse(path.c_str()); } catch (const XMLException & toCatch) { char * message = XMLString::transcode(toCatch.getMessage()); cout << "Exception message is: \n" << message << "\n"; XMLString::release(&message); return false; } catch (const DOMException& toCatch) { char * message = XMLString::transcode(toCatch.msg); cout << "Exception message is: \n" << message << "\n"; XMLString::release(&message); return false; } catch (...) { cout << "Unexpected Exception \n" ; return false; } DOMDocument * domDocument = parser->getDocument(); removeBaseAttr(domDocument); // get a serializer, an instance of DOMLSSerializer XMLCh tempStr[3] = {chLatin_L, chLatin_S, chNull}; DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr); DOMLSSerializer *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer(); DOMLSOutput *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput(); // set user specified output encoding theOutputDesc->setEncoding(0); XMLDOMErrorReporter * xmlDOMErrorReporter = new XMLDOMErrorReporter(); DOMConfiguration * serializerConfig = theSerializer->getDomConfig(); serializerConfig->setParameter(XMLUni::fgDOMErrorHandler, xmlDOMErrorReporter); // set feature if the serializer supports the feature/mode if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTSplitCdataSections, true)) serializerConfig->setParameter(XMLUni::fgDOMWRTSplitCdataSections, true); if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true)) serializerConfig->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true); if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, false)) serializerConfig->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, false); if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTBOM, false)) serializerConfig->setParameter(XMLUni::fgDOMWRTBOM, false); /* XMLFormatTarget * myFormTarget = new StdOutFormatTarget(); theOutputDesc->setByteStream(myFormTarget); theSerializer->write(domDocument, theOutputDesc); */ MemBufFormatTarget * myFormTarget = new MemBufFormatTarget(); theOutputDesc->setByteStream(myFormTarget); theSerializer->write(domDocument, theOutputDesc); /* XMLFormatTarget * myFormTarget2 = new StdOutFormatTarget(); theOutputDesc->setByteStream(myFormTarget2); theSerializer->write(domDocument, theOutputDesc); */ MemBufInputSource * memInput = new MemBufInputSource(myFormTarget->getRawBuffer(), myFormTarget->getLen(), path.c_str()); XercesDOMParser * parser2 = new XercesDOMParser(); parser2->setDoNamespaces(true); parser2->setDoXInclude(true); // parser2->setValidationScheme(XercesDOMParser::Val_Always); // parser2->setDoSchema(true); // parser2->setValidationSchemaFullChecking(true); parser2->setErrorHandler(xmlParseErrorReporter); try { parser2->parse(*memInput); } catch (const XMLException & toCatch) { char * message = XMLString::transcode(toCatch.getMessage()); cout << "Exception message is: \n" << message << "\n"; XMLString::release(&message); return false; } catch (const DOMException& toCatch) { char * message = XMLString::transcode(toCatch.msg); cout << "Exception message is: \n" << message << "\n"; XMLString::release(&message); return false; } catch (...) { cout << "Unexpected Exception \n" ; return false; } DOMDocument * domDocument2 = parser2->getDocument(); XMLNodeFilter * xmlNodeFilter = new XMLNodeFilter(); DOMTreeWalker * domTreeWalker = domDocument->createTreeWalker(domDocument2, DOMNodeFilter::SHOW_ALL, xmlNodeFilter, true); this->serverConfig = extractServerConfig(domDocument2, domTreeWalker); domTreeWalker->release(); delete xmlNodeFilter; delete xmlDOMErrorReporter; delete xmlParseErrorReporter; delete parser; XMLPlatformUtils::Terminate(); return true; }
//======================================================================= void geometryLoader::loadXML(std::string configFile) { // Initialize XERCES-C try { XMLPlatformUtils::Initialize(); } catch(const XMLException &toCatch) { XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n" << " Exception message:" << toCatch.getMessage() << XERCES_STD_QUALIFIER endl; exit(-1); } struct stat fileStatus; int returnStatus = stat(configFile.c_str(), &fileStatus); if( returnStatus == ENOENT ) { ss_.str("") ; ss_ << "ABORT: Path to " << configFile << " does not exist, or path is an empty string." ; STDLINE(ss_.str(),ACRed) ; exit(-1) ; } else if( returnStatus == ENOTDIR ) { ss_.str("") ; ss_ << "ABORT: A component of the path of " << configFile << " is not a directory."; STDLINE(ss_.str(),ACRed) ; exit(-1) ; } else if( returnStatus == ELOOP ) { ss_.str("") ; ss_ << "ABORT: Too many symbolic links encountered while traversing the path to " << configFile; STDLINE(ss_.str(),ACRed) ; exit(-1) ; } else if( returnStatus == EACCES ) { ss_.str("") ; ss_ << "ABORT: Permission denied to read " << configFile; STDLINE(ss_.str(),ACRed) ; exit(-1) ; } else if( returnStatus == ENAMETOOLONG ) { ss_.str("") ; ss_ << "ABORT: Cannot read " << configFile; STDLINE(ss_.str(),ACRed) ; exit(-1) ; } else if( returnStatus == -1 ) { ss_.str("") ; ss_ << "ABORT: Could not find configuration file " << "'" << configFile << "'!"; STDLINE(ss_.str(),ACRed) ; exit(-1) ; } static XercesDOMParser::ValSchemes gValScheme = XercesDOMParser::Val_Auto; // gValScheme = XercesDOMParser::Val_Never; // gValScheme = XercesDOMParser::Val_Auto; // gValScheme = XercesDOMParser::Val_Always; XercesDOMParser *parser = new XercesDOMParser(); parser->setValidationScheme(gValScheme); DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter(); parser->setErrorHandler(errReporter); try { parser->parse(configFile.c_str()); } catch (const OutOfMemoryException&) { STDLINE("F A T A L E R R O R (A): ",ACRed) ; XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl; exit(-1) ; } catch (const XMLException& e) { STDLINE("F A T A L E R R O R (B): ",ACRed) ; XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n Message: " << xercesc::XMLString::transcode(e.getMessage()) << XERCES_STD_QUALIFIER endl; exit(-1) ; } catch (const DOMException& e) { STDLINE("F A T A L E R R O R (C): ",ACRed) ; const unsigned int maxChars = 2047; XMLCh errText[maxChars + 1]; XERCES_STD_QUALIFIER cerr << "\nDOM Error during parsing: '" << configFile << "'\n" << "DOMException code is: " << e.code << XERCES_STD_QUALIFIER endl; if (DOMImplementation::loadDOMExceptionMsg(e.code, errText, maxChars)) XERCES_STD_QUALIFIER cerr << "Message is: " << xercesc::XMLString::transcode(errText) << XERCES_STD_QUALIFIER endl; exit(-1) ; } catch (...) { STDLINE("F A T A L E R R O R (D): ",ACRed) ; XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n " << XERCES_STD_QUALIFIER endl; exit(-1) ; } STDLINE("Configuration successfully parsed",ACGreen) ; DOMDocument * xmlDoc = parser->getDocument(); testBeamGeometryXml_ = xmlDoc->getDocumentElement(); if( !testBeamGeometryXml_ ) { STDLINE("F A T A L E R R O R: ",ACRed) ; XERCES_STD_QUALIFIER cerr << "Empty configuration file\n " << XERCES_STD_QUALIFIER endl; XERCES_STD_QUALIFIER cerr << "This should never occur, the parser should have already detected this error!\n " << XERCES_STD_QUALIFIER endl; exit(-1) ; } theGeometry_->setGeometryFileName(configFile); }
void ClsSettingsReader::parseBuffer(string strFileName) { #ifdef DEBUG_CLSSETTINGSREADER cout << "ClsSettingsReader::parseBuffer()" << endl; #endif cout << "reading settings from: " << strFileName << endl; static bool gDoNamespaces = false; if(!bXMLPlatformInitialized){ try { XMLPlatformUtils::Initialize(); } catch(const XMLException& toCatch) { cerr << "Error during Xerces-c Initialization.\n" << " Exception message:" << toCatch.getMessage() << endl; bXMLPlatformInitialized = false; return; } bXMLPlatformInitialized = true; } //-------------------- XercesDOMParser* parser = new XercesDOMParser(); parser->setValidationScheme(XercesDOMParser::Val_Never); /* XercesDOMParser::Val_Never; XercesDOMParser::Val_Auto; XercesDOMParser::Val_Always; */ // cout << __FILE__ << ":" << __LINE__ << endl; parser->setDoNamespaces(gDoNamespaces); ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase(); parser->setErrorHandler(errHandler); // cout << __FILE__ << ":" << __LINE__ << endl; bool errorsOccured = false; try { parser->parse(strFileName.c_str()); int errorCount = parser->getErrorCount(); if (errorCount > 0){ errorsOccured = true; } } catch (const XMLException& e) { cerr << "An error occured during parsing (XMLException)\n NMessage: " << XMLString::transcode(e.getMessage()) << endl; ClsSettingsReaderException clsSettingsReaderException(XMLString::transcode(e.getMessage())); errorsOccured = true; throw clsSettingsReaderException; } catch (const DOMException& e) { cerr << "An error occured during parsing (DOMException)\n DMessage: " << XMLString::transcode(e.msg) << endl; ClsSettingsReaderException clsSettingsReaderException(XMLString::transcode(e.msg)); errorsOccured = true; throw clsSettingsReaderException; } catch (const SAXException& e) { cerr << "An error occured during parsing (SAXException)\n DMessage: " << XMLString::transcode(e.getMessage()) << endl; ClsSettingsReaderException clsSettingsReaderException(XMLString::transcode(e.getMessage())); errorsOccured = true; throw clsSettingsReaderException; } catch (...) { cerr << "An error occured during parsing\n " << endl; errorsOccured = true; ClsSettingsReaderException clsSettingsReaderException(ClsSettingsReaderException::PARSE_ERROR); throw clsSettingsReaderException; } if (errorsOccured){ cerr << "An error occured during parsing\n " << endl; ClsSettingsReaderException clsSettingsReaderException(ClsSettingsReaderException::PARSE_ERROR); throw clsSettingsReaderException; } if (!errorsOccured) { DOMNode* dnIqrSetting; DOMNodeList* dnlstTemp; ddocIqrSetting = parser->getDocument(); // first we have to find the top System node dnlstTemp = ddocIqrSetting->getElementsByTagName(XMLString::transcode((const char*)"iqrSetting")); dnlstTemp = ddocIqrSetting->getElementsByTagName(XMLString::transcode(ClsTagLibrary::iqrSettings())); if ( dnlstTemp->getLength() == 1){ dnIqrSetting = dnlstTemp->item(0); } else if ( dnlstTemp->getLength() < 1) { ClsSettingsReaderException clsSettingsReaderException(ClsSettingsReaderException::NO_IQRSETTING_NODE); throw clsSettingsReaderException; } iSysSettingReaderState = PARSER_BUFFER_PARSED; } delete errHandler; // delete parser; };
list<ClsDataClientConfig> ClsDataClientConfigReader::getDataClientConfig(string strFileName) { #ifdef DEBUG_CLSDATACLIENTCONFIGREADER cout << "ClsDataClientConfigReader::getDataClientConfig()" << endl; #endif list<ClsDataClientConfig> lstConfigs; #ifdef DEBUG_CLSDATACLIENTCONFIGREADER cout << "reading settings from: " << strFileName << endl; #endif bool errorsOccured = false; static bool gDoNamespaces = false; if(!bXMLPlatformInitialized){ try { XMLPlatformUtils::Initialize(); } catch(const XMLException& toCatch) { cerr << "Error during Xerces-c Initialization.\n" << " Exception message:" << toCatch.getMessage() << endl; bXMLPlatformInitialized = false; errorsOccured = true; // return; } bXMLPlatformInitialized = true; errorsOccured = false; } //-------------------- if (!errorsOccured) { XercesDOMParser* parser = new XercesDOMParser(); parser->setValidationScheme(XercesDOMParser::Val_Never); /* XercesDOMParser::Val_Never; XercesDOMParser::Val_Auto; XercesDOMParser::Val_Always; */ parser->setDoNamespaces(gDoNamespaces); ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase(); parser->setErrorHandler(errHandler); try { parser->parse(strFileName.c_str()); int errorCount = parser->getErrorCount(); if (errorCount > 0){ errorsOccured = true; } } catch (const XMLException& e) { cerr << "An error occured during parsing (XMLException)\n NMessage: " << XMLString::transcode(e.getMessage()) << endl; ClsDataClientConfigReaderException clsDataClientConfigReaderException(XMLString::transcode(e.getMessage())); errorsOccured = true; throw clsDataClientConfigReaderException; } catch (const DOMException& e) { cerr << "An error occured during parsing (DOMException)\n DMessage: " << XMLString::transcode(e.msg) << endl; ClsDataClientConfigReaderException clsDataClientConfigReaderException(XMLString::transcode(e.msg)); errorsOccured = true; throw clsDataClientConfigReaderException; } catch (const SAXException& e) { cerr << "An error occured during parsing (SAXException)\n DMessage: " << XMLString::transcode(e.getMessage()) << endl; ClsDataClientConfigReaderException clsDataClientConfigReaderException(XMLString::transcode(e.getMessage())); errorsOccured = true; throw clsDataClientConfigReaderException; } catch (...) { cerr << "An error occured during parsing\n " << endl; errorsOccured = true; ClsDataClientConfigReaderException clsDataClientConfigReaderException(ClsDataClientConfigReaderException::PARSE_ERROR); throw clsDataClientConfigReaderException; } /* DOMNode* dnIqrConfig; */ DOMDocument *ddocConfig = parser->getDocument(); DOMNodeList* dnlstClients = ddocConfig->getElementsByTagName(XMLString::transcode(ConfigTagLibrary::DataClientTag())); try{ if(dnlstClients->getLength()>0){ DOMNode* dnValue = NULL; unsigned int ii = 0; while( ii< dnlstClients->getLength()){ DOMNode* dnClient = dnlstClients->item(ii); ii++; string strType = getAttributeValue(dnClient, ConfigTagLibrary::TypeTag(), true); string strID = getAttributeValue(dnClient, ConfigTagLibrary::IDTag(), false); ClsDataClientConfig clsDataClientConfig(strID, strType); DOMNodeList* dnlstClientChildren = dnClient->getChildNodes(); unsigned int i2 = 0; while( i2< dnlstClientChildren->getLength()){ DOMNode* dnClientChild = dnlstClientChildren->item(i2); if(dnClientChild->getNodeType() == 1){ string strName = XMLString::transcode(dnClientChild->getNodeName()); if(!strName.compare(ConfigTagLibrary::PositionTag())){ int iX = 0; int iY = 0; iX = iqrUtils::string2int(getAttributeValue(dnClientChild, ConfigTagLibrary::PositionXTag(), true)); iY = iqrUtils::string2int(getAttributeValue(dnClientChild, ConfigTagLibrary::PositionYTag(), true)); clsDataClientConfig.setPosition(iX, iY); } else if(!strName.compare(ConfigTagLibrary::Geometry())){ int iWidth = 0; int iHeight = 0; iWidth = iqrUtils::string2int(getAttributeValue(dnClientChild, ConfigTagLibrary::GeometryWidthTag(), true)); iHeight = iqrUtils::string2int(getAttributeValue(dnClientChild, ConfigTagLibrary::GeometryHeightTag(), true)); clsDataClientConfig.setGeometry(iWidth, iHeight); } else if(!strName.compare(ConfigTagLibrary::StateVariableDisplayTag())){ DOMNodeList* dnlstSVD = dnClientChild->getChildNodes(); unsigned int i3 = 0; while( i3< dnlstSVD->getLength()){ DOMNode* dnSVD = dnlstSVD->item(i3); if(dnSVD->getNodeType() == 1){ string strSVDID = getAttributeValue(dnSVD, ConfigTagLibrary::IDTag(), true); //-- string strItemType = getAttributeValue(dnSVD, ConfigTagLibrary::TypeTag(), true); string strItemID = getAttributeValue(dnSVD, ConfigTagLibrary::ItemIDTag(), true); string strSelectedIndices = getAttributeValue(dnSVD, ConfigTagLibrary::SelectedIndicesTag(), true); ClsStateVariableDisplayConfig clsStateVariableDisplayConfig(/*strItemType,*/ strSVDID, strItemID, strSelectedIndices); DOMNodeList* dnlstSVDParams = dnSVD->getChildNodes(); unsigned int i4 = 0; while( i4< dnlstSVDParams->getLength()){ DOMNode* dnSVDParam = dnlstSVDParams->item(i4); if(dnSVDParam->getNodeType() == 1){ string strParamName = XMLString::transcode(dnSVDParam->getNodeName()); dnValue = dnSVDParam->getFirstChild(); string strParamValue = ""; if(dnValue!=NULL){ strParamValue = XMLString::transcode(dnValue->getNodeValue()); } pair<string, string> pParam(strParamName, strParamValue); clsStateVariableDisplayConfig.addParameter(pParam); } i4++; } clsDataClientConfig.addStateVariableDisplayConfig(clsStateVariableDisplayConfig); } i3++; } } else { string strValue = ""; dnValue = dnClientChild->getFirstChild(); if(dnValue!=NULL){ strValue = XMLString::transcode(dnValue->getNodeValue()); } pair<string, string> pParam(strName, strValue); clsDataClientConfig.addParameter(pParam); } } i2++; } lstConfigs.push_back(clsDataClientConfig); } } } catch (...) { ClsDataClientConfigReaderException clsDataClientConfigReaderException(ClsDataClientConfigReaderException::PARSE_ERROR); throw clsDataClientConfigReaderException; } delete errHandler; } return lstConfigs; };
UINT APIENTRY CXMLDOMDocument::ParseThread(void *pParm) { ATLTRACE(_T("CXMLDOMDocument::ParseThread\n")); CXMLDOMDocument *pThis = reinterpret_cast<CXMLDOMDocument *> (pParm); if (NULL == pThis) return 0; if (!pThis->m_bAbort && pThis->m_FileName.length() > 0) { CBindStatCallbackObj *pCallbackObj = NULL; HRESULT hr = CBindStatCallbackObj::CreateInstance(&pCallbackObj); if (S_OK != hr) pCallbackObj = NULL; if (pCallbackObj != NULL) { pCallbackObj->AddRef(); pCallbackObj->m_pDoc = pThis; } TCHAR name[MAX_PATH] = _T(""); if (pThis->m_bAsync) pThis->PostMessage(MSG_READY_STATE_CHANGE,1); hr = URLDownloadToCacheFile(NULL,pThis->m_FileName,name,URLOSTRM_GETNEWESTVERSION,0,pCallbackObj); if (pCallbackObj != NULL) pCallbackObj->Release(); if (E_ABORT == hr) pThis->m_bAbort = true; else { if (S_OK != hr) { _bstr_t error = _T("Failed to download ") + pThis->m_FileName + _T(": "); _com_error comError(hr); error += comError.ErrorMessage(); pThis->m_pParseError->SetData(1,pThis->m_FileName,error,_T(""),0,0,0); pThis->m_bParseError = true; } } if (S_OK == hr) { pThis->m_FileName = name; if (pThis->m_bAsync) pThis->PostMessage(MSG_READY_STATE_CHANGE,2); } } XercesDOMParser parser; // // If set to true then an node supporting IXMLDOMProcessingInstruction // is added for the XML declaration. // // Setting to true in a custom DLL will better mimic // MSXML.DLL but at a cost of conformance errors // using David Brownell's suite //parser.setToCreateXMLDeclTypeNode(false); parser.setIncludeIgnorableWhitespace(pThis->m_bPreserveWhiteSpace); if (!pThis->m_bParseError && !pThis->m_bAbort) { parser.setDoValidation(pThis->m_bThreadValidate); // // this brings the COM component into better mimicry to MSXML // by not throwing a validation error when there is no DOCTYPE // parser.setValidationScheme(pThis->m_bThreadValidate ? AbstractDOMParser::Val_Auto : AbstractDOMParser::Val_Never); } if (!pThis->m_bParseError && !pThis->m_bAbort) parser.setErrorHandler(pThis); if (!pThis->m_bParseError && !pThis->m_bAbort) pThis->m_pParseError->Reset(); if (!pThis->m_bParseError && !pThis->m_bAbort) pThis->m_bParseError = false; try { if (!pThis->m_bParseError && !pThis->m_bAbort) { if (pThis->m_FileName.length() > 0) parser.parse(static_cast<LPCTSTR> (pThis->m_FileName)); else { XMLByte *pXMLByte = reinterpret_cast<XMLByte*> (static_cast<XMLCh*>(pThis->m_xml)); MemBufInputSource memBufIS(pXMLByte,pThis->m_xml.length()*sizeof(XMLCh),OLESTR("IBMXMLParser"),false); memBufIS.setEncoding(OLESTR("UTF-16LE")); if (!pThis->m_bParseError && !pThis->m_bAbort) parser.parse(memBufIS); } } } catch(...) { pThis->m_bParseError = true; return 0; } if (!pThis->m_bParseError && !pThis->m_bAbort) pThis->m_TmpDocument = parser.adoptDocument(); if (!pThis->m_bParseError && !pThis->m_bAbort && pThis->m_bAsync) pThis->PostMessage(MSG_READY_STATE_CHANGE,4); return 0; }
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; }