[经验总结]MSXML错误处理代码

用MSXML组件处理XML文档出错时,需要给出详细的错误信息。大部分代码只是简单的返回错误提示,SDK文档也没给出例程,无奈之下只得又求助于Google代码搜索,还好,很快就找到合适的例程,稍微改造一下,纳入自己的代码库。

 

 

错误处理代码如下:

 

 

MSXML2::IXMLDOMParseError *pXMLError = NULL; // For XML errors LONG nErrorCode = E_FAIL; // For error codes if(pXMLLicenseDoc->loadXML(m_sLicense) != VARIANT_TRUE) // failed to load the license { wstring wstrErr; (wstrErr).assign(L"/r/n"); (wstrErr).append(L"Failed to load the License /r/n"); hr = pXMLLicenseDoc->get_parseError(&pXMLError); if(NULL != pXMLError) { hr = pXMLError->get_errorCode(&nErrorCode); if (nErrorCode != 0) { wstring wstrTmpErr; hr = ReportError(&wstrTmpErr, pXMLError); (wstrErr).append(wstrTmpErr); } pXMLError->Release(); } return -1; } //END IF 

 

统一的错误报告由下面的ReportError函数生成:

//------------------------------------------------------------------------- //--FUNCTION ReportError //------------------------------------------------------------------------- //--This function is used for reporting parsing errors which occur during the // loading of xml into a IXMLDOMDocument2Ptr object. //--Parameters: // wostream &wout-> a wide output stream to which the error report will be output to. // IXMLDOMParseError *pXMLError -> contains the error info. //------------------------------------------------------------------------- HRESULT CGUtil::ReportError(wstring* pwstrErr, MSXML2::IXMLDOMParseError *pXMLError) { long line; long linePos; LONG errorCode; BSTR pBReason = NULL; HRESULT hr; if(NULL == pXMLError) { return E_INVALIDARG; }//END IF hr = pXMLError->get_line(&line); if (SUCCEEDED(hr)) { hr = pXMLError->get_linepos(&linePos); if (SUCCEEDED(hr)) { hr = pXMLError->get_errorCode(&errorCode); if (SUCCEEDED(hr)) { hr = pXMLError->get_reason(&pBReason); if (SUCCEEDED(hr)) { (*pwstrErr) += pBReason; if (line > 0) { (*pwstrErr).append(L"Error on line "); char num1 [10]; _itoa(line, num1, 10); BSTR bs = _com_util::ConvertStringToBSTR(num1); (*pwstrErr).append(bs); (*pwstrErr).append(L", position "); _itoa(linePos, num1, 10); bs = _com_util::ConvertStringToBSTR(num1); (*pwstrErr).append(bs); (*pwstrErr).append(L"."); }//END IF }//END IF }//END IF }//END IF }//END IF if(NULL != pBReason) SysFreeString(pBReason); //END IF return hr; }//END FUNCTION ReportError 

 

上述代码参考这个链接:    http://www.google.com/codesearch/p?hl=zh-CN#iA8V4e3Y9hQ/ittf/PubliclyAvailableStandards/c043931_ISO_IEC_14496-5_2001_Amd_9_2007_Reference_Software.zip%7CM6AqbSWOJ78/C043931e_Electronic_inserts/Systems/Systems/IM1/IPMP-X/IPMP_RELTool/CGUtil.cpp&q=msxml%20loadXML%20lang:c++&d=9

 

再次感谢Google,将有用的信息带给我们,给予程序员们更好的学习机会和无尽的自由! 

在此描述您的新便笺。

你可能感兴趣的:(function,Google,null,reference,output,Parsing)