First is the header file:
#include <msxml.h>
Initializing a COM environment:
hr = CoInitializeEx(NULL, 0);
To create an XML DOM object:
IXMLDOMDocument *pDOM = NULL;
hr = CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
IID_IXMLDOMDocument, (LPVOID*)&pDOM);
Then there is the loading of the XML content, loaded in two ways, loaded from the file and loaded from the string:
// 从文件加载
VARIANT vt;
VARIANT_BOOL fSuccess;
vt.vt = VT_BSTR;
vt.bstrVal = SysAllocString(szPath);
hr = pDOM->load(vt, &fSuccess);
// 从字符串加载,第一个参数的类型是 BSTR,不过 LPWSTR 也没关系
// 如果项目的预处理器没有设置 UNICODE 之类的东西,就用 char* 吧
LPWSTR xmlSource = TEXT(“<Root/>”)
hr = pDOM->loadXML(xmlSource, &fSuccess);
After you get the DOM object, you can create a new element or node directly, or you can start traversing from the root node, or you can select the node you want to handle directly.
Select the root node:
IXMLDOMElement* pRoot = NULL;
hr = pDom->get_documentElement(&pRoot);
The IXMLDOMNodeList interface is needed to start the traversal from the root node:
IXMLDOMNodeList* pNodeList = NULL;
hr = pRoot->get_childNodes(&pNodeList);
IXMLDOMNode* pNode = NULL;
hr = pNodeList->nextNode(&pNode); // 注意这个返回值,你可以不管它,但不要用 hr != S_OK 判断
while( pNode != NULL )
{
// 干你想干的任何事,然后得到下一个节点
hr = pNodeList->nextNode(&pNode); /
}
Only the IXMLDOMNode interface can be obtained from the ixmldomnodelist, and if the other interface needs to be operated, a bit of hand and foot should be done.
1. Interface query, which is useful when you know exactly what type of node it is.
IXMLDOMElement* pElement = NULL;
hr = pNode->QueryInterface(IID_IXMLDOMElement, (void **)&pElement);