2011-10-19 121 views
0

美好的一天。我有parser.h一個sample.cpp(作爲父節點)和main.cpp。我得到 獲取getDocument分段錯誤。誰能幫我...這裏是我的代碼:使用xerces for C++調用getDocument時出現分段錯誤

parser.h

int Parser::Load(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); 
    ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase(); 
    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 (...) { 
     cout << "Unexpected Exception \n"; 
     return -1; 
    } 
} 

sample.cpp的

void Sample::getXmlNodes(ParseXml* xmlParser){ 
    map<std::string, std::string> attribList; 
    xmlParser->xmlDoc = xmlParser->parser->getDocument(); 
    xmlParser->xmlNode = xmlParser->xmlDoc->getFirstChild(); 
    attribList = xmlParser->getNodeAttribute(xmlParser->xmlNode); 
} 

的main.cpp

#include "parser.h" 
#include "sample.cpp" 

int main(int argc,char **argv){ 
    const char* xmlString="sample.xml"; 
    Parser* xmlObj; 
    Sample sampObj; 

    xmlObj->Load(xmlString); 
    sampObj.getXmlNodes(xmlObj); 

    cout << "Done creating object..." << endl; 

    xmlObj->Cleanup(); 
    return 0; 
} 

我不知道什麼是錯在我的代碼...

回答

2

您沒有爲xmlObj分配內存objetc:

Parser xmlObj; 
Sample sampObj; 
xmlObj.Load(xmlString); 
sampObj.getXmlNodes(&xmlObj); 
+0

仍然段錯誤獲取期間:

Parser* xmlObj; Sample sampObj; xmlObj->Load(xmlString); // SIGSEV here, you have no object to invoke 

必須被替換getDocument。我試過 XercesDOMParser *解析器; DOMDocument * xmlDoc; xmlDoc = parser-> getDocument(); 我得到0屬性計數 – joi

+0

發佈您的調試回溯和完整的示例代碼。我不明白什麼'XercesDOMParser *解析器; DOMDocument * xmlDoc; xmlDoc = parser-> getDocument()'的意思。但是,如果沒有更多的信息,我假設你沒有爲XercesDOMParser對象分配內存,同樣,你沒有使用有效的內存分配。爲什麼你使用指針?有沒有像'XercerDOMParser解析器; DOMDocument * xmlDoc = parser.getDocument();' –

+0

這裏是代碼: void Sample :: getXmlNodes(ParseXml * xmlParser){ map attribList; XercesDOMParser *解析器; DOMDocument * xmlDoc; xmlDoc = parser-> getDocument(); // xmlParser-> xmlDoc = xmlParser-> parser-> getDocument(); DOMNode * xmlNode = xmlParser-> xmlDoc-> getFirstChild(); attribList = xmlParser-> getNodeAttribute(xmlParser-> xmlNode); } – joi