我正在尝试使用 IXMLDOMDocument 进行 XML 读/写。我不是好 COM,我不知道我做的事情是对是错。我非常不确定 COM 初始化和释放可能存在一些问题。下面是我的代码,如果由于 COM 导致这里有任何可能的错误/内存泄漏,请告诉我。
void MyClass::ReadXML(BSTR *pVal)
{
IXMLDOMDocument * pXMLDoc;
IXMLDOMNode * pXDN;
HRESULT hr = CoInitialize(NULL);
hr = CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_INPROC_SERVER,
IID_IXMLDOMDocument, (void**)&pXMLDoc);
if (SUCCEEDED(hr))
{
IXMLDOMNode* pEntityNode = CDOMHelpers::InsertDOMElement(pDoc, NULL, L"Person", NULL);
if (SUCCEEDED(hr))
{
SomeClassObject->SerializeXML(pXMLDoc, pXDN);
pXMLDoc->get_xml(pVal);
pXDN->Release(); // Is this proper way to release COM?
pXDN = NULL;
pXMLDoc->Release();
pXMLDoc = NULL;
}
}
}
void SomeOtherClass::SerializeXML(IXMLDOMDocument* pDoc, IXMLDOMNode* pXDN)
{
CStringW text;
IXMLDOMNode* pNewNode;
text.Format(L"%u", Name);
pNewNode = CDOMHelpers::InsertDOMElement(pDoc, pEntityNode, L"Name", text);
text.Format(L"%u", Address);
pNewNode = CDOMHelpers::InsertDOMElement(pDoc, pEntityNode, L"Address", text);
}