1

我使用以下代码在 C++ 中解析 XML 文件。http://www.codeproject.com/Articles/176236/Parsing-an-XML-file-in-aCC-program

现在我想在 hashmap 中填充数据。但是做不到。错误表示无法从 BSTR 转换为 std::string。

这是部分代码...

 MSXML2::IXMLDOMNode *pIParentNode = NULL;
 //Variables to store attribute's name,type and text:    
      BSTR bstrAttrName, bstrAttrType, bstrAttrText;

 typedef std::tr1::unordered_map< std::string, std::string > hashmap;     
      hashmap numbers;

      for(i = 0; i < (NodeListPtr->length); i++)
      {

            if (pIDOMNode) pIDOMNode->Release();            
            NodeListPtr->get_item(i, &pIDOMNode);


            if(pIDOMNode )
            {               

                pIDOMNode->get_nodeTypeString(&bstrNodeType);

                //We process only elements (nodes of "element" type): 
                BSTR temp = L"element";
               pIDOMNode->get_nodeTypeString(&bstrNodeType);

                //We process only elements (nodes of "element" type): 
                BSTR temp = L"element";

                if (lstrcmp((LPCTSTR)bstrNodeType, (LPCTSTR)temp)==0) 
                {


                    pIDOMNode->get_nodeName(&bstrItemNode);                 
                    printf("Node: %ls\n", bstrItemNode);        


                    pIDOMNode->get_text(&bstrItemText);
                    printf("Text: %ls\n", bstrItemText);

numbers[(std::string)bstrItemNode] = (std::string)bstrItemText; // Here error.. need string..

我试过跟随,但它只返回一个字符。

numbers[(char*)bstrItemNode] = (char*)bstrItemText; // return only 1 character..need whole string..

谁能告诉我如何从这个类中访问字符串来填充哈希图?

错误是:

error C2440: 'type cast' : cannot convert from 'BSTR' to 'std::string'
1>        No constructor could take the source type, or constructor overload resolution was ambiguous
1> : error C2440: 'type cast' : cannot convert from 'BSTR' to 'std::string'
1>        No constructor could take the source type, or constructor overload resolution was ambiguous

请帮帮我,我卡住了。任何替代方式也很感激。谢谢...

4

1 回答 1

0

您不能从 BSTR 转换为 std::string。你必须转换它

作为旁注,BSTR 支持宽字符串,您可能要考虑使用std::wstring而不是当前使用的窄字符串。此外,我建议使用而不是您在此处使用_bstr_t的纯对象。将为您管理内存并使转换更容易(请参阅上面使用 _bstr_t 进行转换的链接)。您仍然可以通过and方法将 _bstr_t 传递给方法,具体取决于您是否需要可修改的引用(有关示例,请参见_bstr_t上的文档)。BSTR_bstr_tGetAddressGetBSTR

于 2012-04-09T17:18:29.163 回答