#include "stdafx.h"
inline void IndentedPrint (int indent, char* format, ...)
{
char m_Message[512];
va_list args;
va_start(args, format);
vsprintf_s(m_Message, format, args);
va_end(args);
printf ("%*s%s", indent, "\t", m_Message);
}
void DisplayAttribute (XmlNode node, int depth)
{
IndentedPrint (depth, "type: %s name: %s value: %s \n",
NodeTypeString (node->nodeType),
(const char*) node->nodeName,
(const char*) (_bstr_t) node->nodeValue);
}
void DisplayNode (XmlNode node, int depth = 0);
void DisplayNodes (XmlNodeList nodes, int depth)
{
for (int i=0; i<nodes->length; i++)
{
DisplayNode (nodes->item[i], depth);
}
}
void DisplayNode (XmlNode node, int depth)
{
IndentedPrint (depth, "type: %s name: %s",
NodeTypeString (node->nodeType),
(const char*) node->nodeName);
if (node->nodeType == MSXML2::NODE_TEXT)
{
IndentedPrint (0, "text: %s\n",
(const char*) (_bstr_t) node->nodeValue);
}
else
{
printf ("\n");
XmlNamedNodeMap attrMap = node->attributes;
if (attrMap)
{
for (int i=0; i<attrMap->length; i++)
{
DisplayAttribute (
attrMap->item[i], depth);
}
IndentedPrint (depth, "\n");
}
XmlNodeList childNodes = node->childNodes;
if (childNodes)
DisplayNodes (childNodes, depth + 5);
}
}
void DisplayXPath (char* xmlFileName, char* xpath)
{
XmlDocument xmlDoc (CLSID_DOMDocument60);
VARIANT_BOOL ok = xmlDoc->load(xmlFileName);
if (! ok)
throw Error ("Failed to load %s", xmlFileName);
printf ("Entire document\n");
DisplayNode (xmlDoc->documentElement, 5);
printf ("Nodes in %s\n", xpath);
XmlNodeList nodeList = xmlDoc->selectNodes(xpath);
DisplayNodes (nodeList, 5);
}
void main(int argc, char* argv[])
{
ComInit com;
try
{
DisplayXPath ("books.xml", "//@*");
}
catch (Error e)
{
printf (e);
}
catch (_com_error e)
{
printf (e.ErrorMessage());
}
printf ("\nDone\n");
_getch ();
}