I’ve used following code for parsing XML file in c++. http://www.codeproject.com/Articles/176236/Parsing-an-XML-file-in-a-C-C-program.
Now I want to fill data in hashmap. But can’t able to do it. Error says conversion not possible to std::string from BSTR.
Here is part of code…
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..
I tried following but it return only one character.
numbers[(char*)bstrItemNode] = (char*)bstrItemText; // return only 1 character..need whole string..
Can anyone tell me that how can I access string from this class to fill in the hashmap??
Error is:
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
Please help me, I’m stuck. Any alternative way also appreciate. Thanks…
You can’t cast from a BSTR to a std::string. You have to convert it.
As a side note, BSTR’s support wide character strings, you probably want to consider using
std::wstringinstead of the narrow string you are currently using. Also, I recommend using_bstr_tinstead of the pureBSTRobjects you are using here._bstr_twill take care of managing the memory for you and make the conversions easier (see the above link that uses _bstr_t for the conversions). You can still pass a _bstr_t off to the methods via theGetAddressandGetBSTRmethods depending on whether you need a modifiable reference or not (see the docs on _bstr_t for examples).