XML Helpers
OTL provides the COtlXMLDocument class to provide a simplified method for creating XML files and editing their content. The class is based on the Microsoft XML parser provided in Internet Explorer. COtlXMLDocument is compatible with recent IE releases. To begin using COtlXMLDocument, create an instance either on the stack or heap, and then read the following section.
Creating an XML Document From Scratch
Use the Create() function to generate an empty XML document. You can specify the root tag name and XML header string as parameters, as shown below:
COtlXMLDocument xDoc;
if(!xDoc.Create( _T("MetaModel"),
_T("<?xml version=\"1.0\" standalone=\"yes\"?>")))
return E_FAIL;
Opening an Existing XML Document
Existing documents can be loaded directly from a file using the LoadFromFile() function, which specifies a full file path, as shown here:
return E_FAIL;
Adding Tags
The AddTag() and AddTextTag() methods create new document tags as children of the root element, or any other element. AddTag() gives you full control of the type of tag to create. AddTextTag() creates two tags: an outer element with an inner text element. This is essentially a name/value pair. For example, the following code results in the following XML added as a child of the root element:
xDoc.AddTextTag(_T("Child"), _T("1234"));
Saving the XML Document to a File
You can save a document directly to a file using the SaveToFile() function, as shown here:
If the file does not exist, it is created. If it exists, it is overwritten.
Reading Tag Values
You can retrieve the value of a tag by searching on the name of the element. Searching is supported by COtlXMLDocument mapping of tag names to values in an STL map. You specify the level in the hierarchy where the map begins using MapElements() and a flat map of all children is generated. LoadMap() can be used instead of MapElements() when the entire file is mapped. You can disable recursion with a parameter to MapElements(). You can generate maps multiple times during a session. Every time MapElements() or LoadMap() is called, the contained STL map is cleared and populated with new value pairs. Once the map is generated, you can use FindTextTag() to get its associated text as a string or variant. For example, the <Child>1234</Child> tag can be read as a variant of type long integer like this:
CComVariant vaVal;
if(xDoc.FindTextTag("CHILD", vaVal, VT_I4))
If you already have an IXMLElement pointer, its associated text value can be retrieved using GetTextTag() instead.
Trace Output
COtlXMLDocument has debug facilities for dumping the contents of an XML element and its children to the Visual Studio debug output window. Use the TRACE_ELEMENT() function with no parameters to show the contents of the root element only. Use TRACE_ELEMENT(IXMLElement* pElem) to show all children of pElem.
NOTE >> TRACE_ELEMENT() is a function name—not a macro.