VC++通过MSXML6来操作xml需要注意的内存泄漏问题

VC++通过MSXML6来操作xml需要注意的内存泄漏问题

1. 创建IXMLDOMDocument 对象,注:在使用完成后需要release,而不是立马release,立马释放了就没法使用了

     HRESULT hr;
IXMLDOMDocument *pXmlDoc = NULL;
 
hr = CoCreateInstance(__uuidof(DOMDocument),NULL,CLSCTX_INPROC_SERVER,

__uuidof(IXMLDOMDocument),(void**)&pXmlDoc);


        pXmlDoc->Release();

2. 获取IXMLDOMNode, 同上,需要使用完成后释放

     IXMLDOMNode* pXMLFirstChild = NULL;

pIXMLDOMDocument->get_firstChild(&pXMLFirstChild);


        pXMLFirstChild.Release();

3. 获取属性集IXMLDOMNamedNodeMap,  同上,需要使用完成后释放

     IXMLDOMNamedNodeMap* pXMLAttributeMap = NULL;
if (pXMLFirstChild)
{
pXMLFirstChild->get_attributes(&pXMLAttributeMap);

}


        pXMLAttributeMap.Release();

4. 创建属性IXMLDOMAttribute, 同上,需要使用完成后释放

IXMLDOMAttribute* pEncodeAttribute=NULL;
pIXMLDOMDocument->createAttribute( L"encoding",&pEncodeAttribute);

pXMLAttributeMap->setNamedItem(pEncodeAttribute, &pXMLEncodNode);


        pEncodeAttribute.Release();


5. 获取节点内容,需要释放

BSTR bstr = NULL;

pNode->get_text( &bstr);

if(bstr)

{

SysFreeString(bstr);

}

猜你喜欢

转载自blog.csdn.net/aidansen/article/details/80979076