perfectxml.com
 Basic Search  Advanced Search   
Topics Resources Free Library Software XML News About Us
home » focus » msxml » ask a question » past questions & answers Tuesday, 14 August 2007
 
NEWS
MSXML 4.0 SP2 now available!

 
MSXML
Basics
DOM
SAX
XPath
XSLT
Schemas
SOM
HTTP Access
.NET
Data Islands
Ask a Question
   Past Q&As
C++ Samples
DLL/Version Info
Reference Guide
Books
KB Articles
   HOW TO
   SAMPLE
   INFO
   BUG/PRB
   FIX
   Misc.
MSXML Tips
   August 2002
   September 2002
MSXML Tools

Microsoft XML Core Services


Go back to list of previously asked questions and answers

Question: Binary to Base64 using MSXML in C++: I have seen many Visual Basic examples on encoding/decoding binary data as Base64 using MSXML. Can you please provide a C++ example to illustrate converting a disk file (letís say a .JPG image) into base64 XML using MSXML?
Asked By: Guest
Viewed: 17268
Answer: Click here to download a sample C++ project that illustrates converting a disk file to base64 encoded XML, and also decode base64 encoded XML to a binary file.


// Base64CPP.cpp : Defines the entry point for the console application.

//    NOTE:
//    This code is provided as is in the form of a sample with no warranties of any kind, 
//    either expressed or implied for any purpose. Use at your own risk.

#include "stdafx.h"

#include <TCHAR.H>
#include <stdio.h>
#include <sys/stat.h>
#include <fstream.h>
#include <string.h>

#include <atlbase.h>
#import <msxml4.dll> named_guids
using namespace MSXML2;

inline void EVAL_HR( HRESULT _hr ) 
   { if FAILED(_hr) throw(_hr); }

//    Binary to Base64 Encoding
bool DoEncoding(LPCTSTR lpszXMLFile, LPCTSTR lpszBinFile)
{
    bool bRetVal = false;
    try
    {
        long lFileSize;
        struct stat fileSizeVal;
        
        //    Get the file size
        if (stat(lpszBinFile, &fileSizeVal) == 0)
        {
            lFileSize = fileSizeVal.st_size;
            if(lFileSize <= 0)
                return false;
        }
        else 
            return false;
        
        //    Instantiate XML DOMDocument
        CComPtr<IXMLDOMDocument2> spXMLDoc;
        CComPtr<IXMLDOMElement> spDataElement;
        HRESULT hr = spXMLDoc.CoCreateInstance(CLSID_DOMDocument40);
        EVAL_HR(hr);
        spXMLDoc->loadXML(_T("<?xml version='1.0' encoding='UTF-8'?> <Data/>"));

        //    Prepare the top node to store binary data as base64
        spDataElement = spXMLDoc->documentElement;
        ATLASSERT(spDataElement != NULL && _T("Failed to get document element."));

        hr = spDataElement->put_dataType(CComBSTR(_T("bin.base64")));
        EVAL_HR(hr);

        //    Read the file into memory
        ifstream binDataFile;
        binDataFile.open(lpszBinFile, ios::binary);
        binDataFile.seekg(ios::beg);
        SAFEARRAY* psa = SafeArrayCreateVector( VT_UI1, 0L, lFileSize);
        binDataFile.read((byte*)psa->pvData, lFileSize);
        binDataFile.close();

        //    Save the binary data into Data node
        VARIANT var;
        VariantInit(&var);
        var.parray = psa;
        var.vt = (VT_ARRAY | VT_UI1 );
        spDataElement->nodeTypedValue = var;

        //    Save the XML Document
        spXMLDoc->save(lpszXMLFile);

        bRetVal = true;
    }
    catch(int)
    {
        //TODO: Error handling
        printf(_T("Exception raised!"));
    }

    return bRetVal;
}

//    Base64 to binary decoding
bool DoDecoding(LPCTSTR lpszXMLFile, LPCTSTR lpszBinFile)
{
    bool bRetVal = false;
    try
    {
        //    Instantiate DOMDocument and load XML file
        CComPtr<IXMLDOMDocument2> spXMLDoc;
        CComPtr<IXMLDOMElement> spDataElement;
        HRESULT hr = spXMLDoc.CoCreateInstance(CLSID_DOMDocument40);
        EVAL_HR(hr);
        CComVariant vtFileName = CComBSTR(lpszXMLFile);
        spXMLDoc->load(vtFileName);

        //    ASSUMPTION: documentElement (top element) contains base64 data
        spDataElement = spXMLDoc->documentElement;
        ATLASSERT(spDataElement != NULL && _T("Failed to get document element."));

        //    Prepare the file for writing
        ofstream binDataFile (lpszBinFile, ios::out | ios::binary);

        //    Save the binary data into data file
        long lDataLength=0;
        hr = SafeArrayGetUBound(spDataElement->nodeTypedValue.parray, 1, &lDataLength);
        EVAL_HR(hr);
        lDataLength++;

        binDataFile.write((byte*)(spDataElement->nodeTypedValue.parray->pvData), lDataLength);
        binDataFile.close();

        bRetVal = true;
    }
    catch(int)
    {
        //TODO: Error handling
        printf(_T("Exception raised!"));
    }

    return bRetVal;
}

int main(int argc, char* argv[])
{
    if(argc < 4)
    {//insufficient parameters
        printf(_T("\nSample app to encode/decode binary data as base64 XML using MSXML.\n"));
        printf(_T("\nUsage:\tBase64CPP.exe <e>|<d> <XMLFileName> <BinaryDataFile>"));
        printf(_T("\n\nExamples:"));
        printf(_T("\n\tEncode binary data in 1.jpg and save as Base64 into 1.xml:"));
        printf(_T("\n\t\tBase64CPP.exe e c:\\1.xml c:\\1.jpg\n"));
        printf(_T("\n\tDecode base64 data in 1.xml and save as binary into 2.jpg:"));
        printf(_T("\n\t\tBase64CPP.exe d c:\\1.xml c:\\2.jpg\n\n"));
        return -1;
    }

    try
    {
        HRESULT hr = CoInitialize(NULL);
        EVAL_HR(hr);

        if(_tcsicmp(argv[1], _T("e")) == 0)
        {
            if(DoEncoding(argv[2], argv[3]))
                printf(_T("Success. See %s for results."), argv[2]);
            else
                printf(_T("Failed."));
        }
        else
        {
            if(DoDecoding(argv[2], argv[3]))
                printf(_T("Success. See %s for results."), argv[3]);
            else
                printf(_T("Failed."));
        }
    }
    catch(int)
    {
        //TODO: Error handling
        printf(_T("Exception raised!"));
    }

    CoUninitialize();
    getchar();
    return 0;
}


Go back to list of previously asked questions and answers
  Contact Us | E-mail Us | Site Guide | About PerfectXML | Advertise ©2004 perfectxml.com. All rights reserved. | Privacy