Problem with writing XML DOM tree to memory buffer.
Hello newsgroup,
I tried to write a small test application that creates an XML DOM tree and writes the contents
into a string buffer (saving to file works perfectly). Unfortunately, I seem to go wrong
at some point (the text displayed contains only question marks :(
Can anybody give me some suggestions?
This code works under Visual C++ 6.0 with MSXML 4.0 installed. If you have a different
version of MSXML, you'll have to replace the version number in the CreateInstance call
of soDocument accordingly to be able to compile this example.
#include <afx.h>
#include <afxwin.h>
#include <comip.h>
#include <comdef.h>
#include <msxml2.h>
#include <atlbase.h>
#include <atlconv.h>
_COM_SMARTPTR_TYPEDEF (IXMLDOMNode, __uuidof (IXMLDOMNode));
_COM_SMARTPTR_TYPEDEF (IXMLDOMDocument2, __uuidof (IXMLDOMDocument2));
_COM_SMARTPTR_TYPEDEF (IXMLDOMAttribute, __uuidof (IXMLDOMAttribute));
_COM_SMARTPTR_TYPEDEF (IXMLDOMElement, __uuidof (IXMLDOMElement));
_COM_SMARTPTR_TYPEDEF (IStream, __uuidof (IStream));
int main ()
{
USES_CONVERSION;
::CoInitialize (NULL);
{
// Create the document and fill it with some example data.
IXMLDOMDocument2Ptr spDocument;
spDocument.CreateInstance(__uuidof(DOMDocument40));
IXMLDOMElementPtr spCurrentNode;
spDocument->createElement (CComBSTR (L"ExposureTime").Detach (), &spCurrentNode);
spCurrentNode->setAttribute (CComBSTR (L"value").Detach (), CComVariant ((double)3.14159));
IXMLDOMNodePtr spUnused;
spDocument->appendChild (spCurrentNode, &spUnused);
// Let the document persist into a memory stream.
IStreamPtr spStream;
HGLOBAL MemoryHandle = ::GlobalAlloc (GMEM_MOVEABLE, 3000);
VERIFY (SUCCEEDED (::CreateStreamOnHGlobal (MemoryHandle, FALSE, (IStream**) &spStream)));
VERIFY (SUCCEEDED (spDocument->save (CComVariant (spStream))));
// I simply guessed, that the stream stores the text as UNICODE, but I also
// tried this with ANSII characters.
CString XMLText = OLE2CT ((const wchar_t*) ::GlobalLock (MemoryHandle));
::AfxMessageBox (XMLText);
}
::CoUninitialize();
return 0;
}
Thanks in advance,
Stuart