Click here to Skip to main content
6,292,811 members and growing! (10,414 online)
Email Password   helpLost your password?
Languages » XML » General     Intermediate

Using MSXML to read XML documents

By ljw1004

How to read XML documents using MSXML, in a modern C++/template manner
XML, VC7, eVC 3.0Win2K, WinXP, Win2003, PocketPC 2002, STL, Dev
Posted:7 Jun 2003
Views:188,752
Bookmarked:54 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
33 votes for this article.
Popularity: 6.02 Rating: 3.97 out of 5
4 votes, 12.1%
1
1 vote, 3.0%
2
2 votes, 6.1%
3
9 votes, 27.3%
4
17 votes, 51.5%
5

Introduction

Everyone needs to parse XML nowadays. I found it hard to find good example source code in C++ -- most of the code seemed written in an old-fashioned style without templates, or were aimed at C# or Visual Basic. Hence, this article provides an example.

Parsing is done using MSXML, and I use ATL "smart pointers" to avoid the need to manually release everything. Note that MSXML is Unicode, through and through. It's a big waste of effort trying to use it with multi-byte/ASCII.

The accompanying source code has project files for embedded Visual C++ (.vcw .vcp), Visual C++ .NET (.sln .vcproj) and and Borland C++Builder5 (.bpr .bpf). But not for Visual C++6, since that didn't ship with recent-enough MSXML headers.

PocketPC considerations: I use XML to store my configuration files. They have grown to about 80k each, and on the PocketPC it takes 2 seconds to parse them. Therefore, I actually parse it into a more efficient memory-block structure, and write this memory block to disk. That way, I only need to re-parse if there have been any changes.

Preliminaries

Setup depends on which development environment you're using:

  • Visual Studio .NET -- fine as it is.
  • Borland C++ Builder -- under Project > Options > Directories, add ($BCB)\include\atl.
  • eMbedded Visual C++ (EVC) -- download the free STL port made by Giuseppe Govi, and put it in a subdirectory "stl_eVC" of your project.
#include <windows.h>

#include <msxml.h>

#include <objsafe.h>

#include <objbase.h>

#include <atlbase.h>

#pragma warning( push )
#pragma warning( disable: 4018 4786)
#include <string>

#pragma warning( pop )
using namespace std;

(The warning-disabler is just for EVC, which generates spurious warnings otherwise.)

Also, CoInitializeEx(NULL,COINIT_MULTITHREADED); beforehand (normally at the start of WinMain), and CoUninitialize(); afterwards (normally at the end of WinMain).

Actually, CoInitialize(NULL) is easier when compiling for desktop win32, since it works on Win'95 and hence doesn't require you to define _WIN32_WINNT. But it's not available on PocketPC.

XML Parsing

This is how to load the XML document. It uses the magic of ATL's safe pointers, to avoid the need to Release() everything afterwards. (For simplicity, error-checking has been omitted.)

CComPtr<IXMLDOMDocument> iXMLDoc;
iXMLDoc.CoCreateInstance(__uuidof(DOMDocument));
     
#ifdef UNDER_CE
// Following is a bugfix for PocketPC.

iXMLDoc->put_async(VARIANT_FALSE);
CComQIPtr<IObjectSafety,&IID_IObjectSafety> isafe(iXMLDoc);
if (iSafety) 
{ DWORD dwSupported, dwEnabled; 
  isafe->GetInterfaceSafetyOptions(IID_IXMLDOMDocument,
                                   &dwSupported,&dwEnabled);
  isafe->SetInterfaceSafetyOptions(IID_IXMLDOMDocument,
                                   dwSupported,0);
}
#endif

// Load the file. 

VARIANT_BOOL bSuccess=false;
// Can load it from a url/filename...

iXMLDoc->load(CComVariant(url),&bSuccess);
// or from a BSTR...

//iXMLDoc->loadXML(CComBSTR(s),&bSuccess);


// Get a pointer to the root

CComPtr<IXMLDOMElement> iRootElm;
iXMLDoc->get_documentElement(&iRootElm);

// Thanks to the magic of CComPtr, we never need call

// Release() -- that gets done automatically.

As for accessing the elements and iterating over them, I wrote a tiny helper class TElem. Here's the example XML document that I'll demonstrate it with:

<?xml version="1.0" encoding="utf-16"?>
<root desc="Simple Prog">
  <text>Hello World</text>
    <layouts>
    <lay pos="15" bold="true"/>
    <layoff pos="12"/>
    <layin pos="17"/>
  </layouts>
</root>

And this is how to use TElem:

TElem eroot(iRootElm);
wstring desc = eroot.attr(L"desc");
// returns "Simple Prog"


TElem etext = eroot.subnode(L"text");
wstring s = etext.val();
// returns "Hello World"

s = eroot.subval(L"text");
// This is a shorter way to achieve the same thing


TElem elays = eroot.subnode(L"layouts");
for (TElem e=elays.begin(); e!=elays.end(); e++)
{ int pos = e.attrInt(L"pos",-1);
  bool bold = e.attrBool(L"bold",false);
  // we suggest defaults, in case the attribute is missing

  wstring id = e.name();
  // returns "lay" or "layoff" or "layin"

}

Again, there's no need to release TElem - that's done automatically. The full list of methods in TElem:

// TElem -- a simple class to wrap up IXMLDomElement

// and to iterate its children.


wstring TElem::name() const;
// in <item>stuff</item> it returns "item"


wstring TElem::val() const;
// in <item>stuff</item> it returns "stuff"


wstring TElem::attr(const wstring name) const;
// in <item name="hello">stuff</item> it returns "hello"

// int x=e.attrInt(L"a",2)

// bool b=e.attrBool(L"a",true),

// We supply defaults in case the attribute was absent.


TElem TElem::subnode(const wstring name) const;
// in <item><a>hello</a><name>there</name></item>

// it returns the TElem <name>there</name>


wstring TElem::subval(const wstring name) const;
// in <item><a>hello</a><name>there</name></item>

// it returns "there"


for (TElem c=e.begin(); c!=e.end(); c++) {...}
// iterates over the subnodes

Source code for TElem

Note in this source code the use of CComPtr and CComQIPtr and CComBSTR. These are lovely "safe-pointers" provided by the ATL, and mean that we needn't bother with Release().

I'm a bit of a miser, and so included iterator functionality in TElem, rather than writing a separate TElemIterator class.

struct TElem
{ CComPtr<IXMLDOMElement> elem;
  CComPtr<IXMLDOMNodeList> nlist; int pos; long clen;

  TElem() :
        elem(0), nlist(0), pos(-1), clen(0) {}
  TElem(int _clen) :
        elem(0),nlist(0),pos(-1),clen(_clen) {}
  TElem(CComPtr<IXMLDOMElement> _elem) :
        elem(_elem), nlist(0), pos(-1), clen(0) {get();}
  TElem(CComPtr<IXMLDOMNodeList> _nlist) :
        elem(0), nlist(_nlist), pos(0), clen(0) {get();}

  void get()
  { if (pos!=-1)
    { elem=0;
      CComPtr<IXMLDOMNode> inode;
      nlist->get_item(pos,&inode);
      if (inode==0) return;
      DOMNodeType type; inode->get_nodeType(&type);
      if (type!=NODE_ELEMENT) return;
      CComQIPtr<IXMLDOMElement> e(inode);
      elem=e;
    }
    clen=0; if (elem!=0)
    { CComPtr<IXMLDOMNodeList> iNodeList;
      elem->get_childNodes(&iNodeList);
      iNodeList->get_length(&clen);  
    }
  }
  //

  wstring name() const
  { if (!elem) return L"";
    CComBSTR bn; elem->get_tagName(&bn);
    return wstring(bn);
  }
  wstring attr(const wstring name) const
  { if (!elem) return L"";
    CComBSTR bname(name.c_str());
    CComVariant val(VT_EMPTY);
    elem->getAttribute(bname,&val);
    if (val.vt==VT_BSTR) return val.bstrVal;
    return L"";
  }
  bool attrBool(const wstring name,bool def) const
  { wstring a = attr(name);
    if (a==L"true" || a==L"TRUE") return true;
    else if (a==L"false" || a==L"FALSE") return false;
    else return def;
  }
  int attrInt(const wstring name, int def) const
  { wstring a = attr(name);
    int i, res=swscanf(a.c_str(),L"%i",&i);
    if (res==1) return i; else return def;
  }
  wstring val() const
  { if (!elem) return L"";
    CComVariant val(VT_EMPTY);
    elem->get_nodeTypedValue(&val);
    if (val.vt==VT_BSTR) return val.bstrVal;
    return L"";
  }
  TElem subnode(const wstring name) const
  { if (!elem) return TElem();
    for (TElem c=begin(); c!=end(); c++)
    { if (c.name()==name) return c;
    }
    return TElem();
  }
  wstring subval(const wstring name) const
  { if (!elem) return L"";
    TElem c=subnode(name);
    return c.val();
  }
  TElem begin() const
  { if (!elem) return TElem();
    CComPtr<IXMLDOMNodeList> iNodeList;
    elem->get_childNodes(&iNodeList);
    return TElem(iNodeList);
  }
  TElem end() const
  { return TElem(clen);
  }
  TElem operator++(int)
  { if (pos!=-1) {pos++; get();}
    return *this;
  }
  bool operator!=(const TElem &e) const
  { return pos!=e.clen;
  }
};

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

ljw1004


Member
Lucian is a researcher at Microsoft in Redmond. As a break from computer science theory, he likes to write practical programs every now and then. Especially screen savers!
Occupation: Web Developer
Location: United States United States

Other popular XML articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 39 (Total in Forum: 39) (Refresh)FirstPrevNext
GeneralCoCreateInstance is not able to create an instance of DOMDocument in Windows Mobile 6 PinmemberMember 42017414:29 3 Oct '08  
GeneralRe: CoCreateInstance is not able to create an instance of DOMDocument in Windows Mobile 6 PinmemberMember 420174120:57 5 Oct '08  
GeneralTrying to work this with Pocket 2003. PinmemberJiwan_a10:12 18 Jun '08  
GeneralWon't compile for SmartPhone 2002 device Pinmemberppcinfo9:44 21 Jan '07  
Generalhow do i add msxml to my installer ? Pinmembercode4jigar3:15 5 Sep '06  
Generalhow to read binaries from xml on windows 98 Pinmemberkcselvaraj23:07 3 Jul '06  
QuestionFailing to load an XML file! Pinmemberiskender.ryskulov@encos.com18:57 1 May '06  
AnswerRe: Failing to load an XML file! Pinmemberraster_blaster14:22 28 Jun '06  
GeneralDo a little research PinmemberKarstenK1:51 10 Apr '06  
GeneralRe: Do a little research Pinmemberljw10046:12 10 Apr '06  
GeneralNeed urgent reply. PinmemberPremViji19:21 26 Mar '06  
QuestionNeed Help to use this parser PinmemberPremViji20:43 23 Mar '06  
GeneralI must add my thanks! PinmemberPeter Weyzen23:07 3 Jan '06  
GeneralThank you for greatsolution! PinmemberMichael Fleetwood7:56 11 Oct '05  
Generalneed help Pinmemberudaysai21:58 4 Aug '05  
GeneralRe: need help Pinmemberudaysai22:07 4 Aug '05  
GeneralUse a XML file Pinmembermomo74:51 20 May '05  
GeneralRe: Use a XML file Pinmembermig16:40 23 May '05  
GeneralImproved TElem Pinmembermig16:40 25 Mar '05  
GeneralRe: Improved TElem PinmemberDaFonz11:27 1 Aug '05  
GeneralMost Excellent Example. PinmemberJuanValdez8:30 17 Sep '04  
GeneralRe: Most Excellent Example. PinmemberJuanValdez22:47 18 Sep '04  
GeneralWell Done Pinmemberbeejoy16:57 2 Jun '04  
GeneralError under EVC 4.0 / Pocket PC 2003 PinmemberIshan22:10 28 Jul '03  
GeneralTElem nu=e where e = CComQIPtr<IXMLDOMElement> Pinmemberbobbino22:18 29 Jun '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 7 Jun 2003
Editor: Nishant Sivakumar
Copyright 2003 by ljw1004
Everything else Copyright © CodeProject, 1999-2009
Web12 | Advertise on the Code Project