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);
}
本文讨论了使用VC++结合MSXML6组件进行XML文件操作时可能遇到的内存泄漏问题,并详细列举了五个常见操作场景下IXMLDOMDocument等COM对象的正确管理方式,包括创建、获取节点及属性、设置属性等。
221

被折叠的 条评论
为什么被折叠?



