CXmlDocument - A simple class to read/write XML documents.
CXmlDocument and CXmlElement are two classes which can be used to work with XML documents.
You can parse existing XML documents or create new ones.
When a document is loaded all elements from the root tag are put into a (child) element list. If these elements have childs of their own, they're also put into a (linked) list.
This way we get a tree structure of all the elements in the document.

The class CXmlElement is used to save the data of an XML element (tag name, data, attributes and child elements).

CString m_strName;// tag name
CString m_strAttributes;// attributes
CString m_strData;// data

CObList m_ChildElements;// child elements

This class encapsulates the XML document.

Member functions:

BOOL Load(LPCTSTR lpszFileName);
Loads the specified XML document into memory.

BOOL Store(LPCTSTR lpszFileName);
Store the XML document to specified filename.

BOOL Parse(LPCTSTR lpszString);
Parse the specified XML string and put elements in linked lists.

CString Generate();
Generate a XML string from all elements in linked lists.
Output is a formated XML string (including spaces and carriage return line feeds).

CXmlElement *AddElement(CXmlElement *pElement, LPCTSTR lpszName, LPCTSTR lpszData, LPCTSTR lpszAttributes);
Add a new element to document in specified level. So the new element will become a child of pElement.
The return value is a pointer to the created element.

CXmlElement *GetRootElement();
Get the root element of the XML document. This is the base element for all other elements.

CXmlElement *GetFirstChild(CXmlElement *pElement);
Get the first child of the specified CXmlElement. This call is usally followed by a call to GetNextSibling().

CXmlElement *GetNextSibling(CXmlElement *pElement);
Get the next child of the specified CXmlElement.


CXmlElement *pRoot = GetRootElement();

CXmlElement *pElement = GetFirstChild(pRoot);
  TRACE1("%s\n", pElement->m_strName);
  pElement = GetNextSibling(pRoot);

CXmlElement *FindElement(CXmlElement *pElement, LPCTSTR lpszName);

Find the first occurrence of the specified tag (= lpszName). This call is usally followed by a call to FindNextElement().

CXmlElement *FindNextElement(CXmlElement *pElement);
Find the next occurrence of a previous specified tag (in FindElement() ).


CXmlElement *pRoot = GetRootElement();

CXmlElement *pElement = FindElement(pRoot, "ITEM");
  TRACE1("%s\n", pElement->m_strName);
  pElement = FindNextElement(pRoot);

This example shows you how to parse an existing XML document:

Download demo executable

Download source code
This class is part of the Pablo Software Solutions MFC Extension Package - Classes Edition

Also check out my other example: MDB2XML, to learn how to create a XML document.


[Home] [Products] [Source Code] [Downloads] [Support]

© 2015 - Pablo Software Solutions
All rights reserved.