在xml操作中经常会用到在某一个节点后或前面插入一个节点,MSXML DOM 中使用的函数是insertBefore(IXMLDOMNode *newChild, VARIANT refChild);第二个参数只的是参考节点的内存地址传参需要用到 _variant_t 的 IDispatch构造方法,代码如下#import "msxml3.dll" rename_namespace("MSXML")void InsertDemo() {
CComPtr<MSXML::IXMLDOMDocument> pDoc;pDoc.CoCreateInstance(__uuidof(MSXML::DOMDocument));pDoc->load(_variant_t("xxx.xml"));
CComPtr<MSXML::IXMLDOMElement> pRoot = pDoc->GetdocumentElement();CComPtr<MSXML::IXMLDOMNodeList> nodeList = pRoot->GetchildNodes();/*创建新节点*/
CComPtr<MSXML::IXMLDOMElement> newElement = pDoc->createElement(_bstr_t("newNode"));
newElement->setAttribute(_bstr_t("key"), _variant_t("value"));/*在第三个节点前插入新节点*/
CComPtr<MSXML::IXMLDOMNode> refNode = nodeList->Getitem(2);pRoot->insertBefore(newElement, _variant_t((IDispatch*)refNode));pDoc->save(_variant_t("xxx.xml"));
}