|
Hi, Alex
I have only one little question: How I can add the string like <?xml version="1.0" encoding="UTF-8"?> in my xml file. I try to do like your suggestion in your old article( insert createProcessingInstruction() in the document constructor). But in this case if I make after then LoadXML(something) to start new tree, the instruction row has been disappeared.
I fixed it now by loading doc from template file, but may be you have a better resolve?
Thanks
|
|
|
|
|
The create processing instructio function is not implemented in this release, but since the class operates on ditect pointers you can ask for raw pointer to the document via Interface() finction and add the instruction yourself.
Creative minds - create creative creations!
|
|
|
|
|
Anyone know what modifications need to be made in order to get this to work with MSXML 4.0 SP2?
Overall, an excellent article alex, thank you!
Dru
|
|
|
|
|
Basically i guess you just need to import msxml4.dll instead of msxml3.dll
And agiain that is only an unchecked guess...
I'll try to check this later when i have time...
Creative minds - create creative creations!
|
|
|
|
|
Yes, but You also have to change the two occurenses of CLSID_DOMDocument to CLSID_DOMDocument40 , or the msxml3.dll will be loaded even though you've #imported "msxml4.dll".
(I struggled with this for a while; I couldn't understand why it would validate my .xml files which contained a reference to a .xsd. Now I know that msxml3 doesn't grok .xsd's.)
Thanks for the classes anyway Alex, even though I hope You will take the time to update it regarding the memory issues. I'm not into this COM stuff, so I can't really do it myself (and I'm lazy, too ).
|
|
|
|
|
Ah that might explain why my application doesn't work at my workplace. I only imported the msxml4.dll and we don't have msxml3.dll installed on our machines. So, the program did nothing.
I'll post the results. I am hopeful now that this was the problem 
|
|
|
|
|
My main problem is that i currently dont understand how msxml.3 works. Im not familiar with it, but this article has helped me allot. If I had to I could break down the wrapper to see who msxml works. However, right now im just tring to get away with plug and play.
I need to parse an xml file that has a scheme and database like records at the bottom, it might resemble...
I used the included application to determine how to parse the tags i wanted, but it seems indirect. This is what im doing now...
<br />
void ParseNode(IDispatch *pNode)<br />
{<br />
CXmlNodeWrapper node(pNode);<br />
<br />
if (node.Name() == "row")<br />
{<br />
for (int i = 0; i < node.NumAttributes(); i++)<br />
{<br />
node.GetAttribName(i); <br />
node.GetAttribVal(i);<br />
<br />
}<br />
}<br />
<br />
for (int i = 0; i < node.NumNodes(); i++)<br />
{<br />
ParseNode( node.GetNode(i), szRec, szFileDate );<br />
}<br />
}<br />
And ild like to use the query function, but i cant seem to figure out how to use it. ie...
CXmlNodeWrapper nodeMode( xmlNode.FindNode("//RowsetSchema:row[@Type='Mode']") );
CXmlNodeWrapper nodeKeyr( xmlNode.FindNode("//RowsetSchema:row[@Type='Keyer']") );
CXmlNodeWrapper nodeC3 ( xmlNode.FindNode("//RowsetSchema:row[@Type='C3']") );
CXmlNodeWrapper nodeC4 ( xmlNode.FindNode("//RowsetSchema:row[@Type='C4']") );
So instead of recursivly looping, ild rather just query for each field in each record individually..
Im a little unsure of the syntax fo the FindNode parameter? I greatly appreciate any insight ^^
thx,
-SD
_____________________________________________________________________
〈xml xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
xmlns:rs='urn:schemas-microsoft-com:rowset'
xmlns:z='#RowsetSchema'〉
〈s:Schema id='RowsetSchema'〉
〈s:ElementType name='row' content='eltOnly' rs:updatable='true'>
〈s:AttributeType name='SortMode' rs:number='1' rs:write='true'>
〈s:datatype dt:type='i1' dt:maxLength='1' rs:precision='0' rs:fixedlength='true' rs:maybenull='false'/〉
〈/s:AttributeType〉
〈s:AttributeType name='Mode' rs:number='2' rs:write='true'>
〈s:datatype dt:type='string' rs:dbtype='str' dt:maxLength='20' rs:precision='0' rs:fixedlength='true' rs:maybenull='false'/〉
〈/s:AttributeType〉
〈s:AttributeType name='Keyer' rs:number='3' rs:write='true'>
〈s:datatype dt:type='string' rs:dbtype='str' dt:maxLength='50' rs:precision='0' rs:fixedlength='true' rs:maybenull='false'/〉
〈/s:AttributeType〉
// ... and so on ....
〈/s:ElementType〉
〈/s:Schema〉
// and here would be the data in the file...
〈rs:data〉
〈rs:insert〉
〈z:row SortMode='11' Mode='COA ADDRESS' Keyer='We**, Ri***' c3='2:34:52' c4='0:00:19'/〉
〈z:row SortMode='10' Mode='COA NON ADDRESS' Keyer='Ti*****, So****' c3='3:37:43' c4='0:00:02'/〉
〈z:row SortMode='10' Mode='COA NON ADDRESS' Keyer='La****, ***cy ' c3='0:57:03' c4='0:00:01'/〉
〈/rs:insert〉
〈/rs:data〉
〈/xml〉
|
|
|
|
|
I got it, Basically , i just needed a way to loop through the records and pull the required fields. Here is what i turned up, course ill have to add it to the api.
<br />
void CXmlDocumentWrapper::Test()<br />
{<br />
long numitems;<br />
<br />
MSXML2::IXMLDOMNodeListPtr items = m_xmldoc->getElementsByTagName("z:row");<br />
<br />
items->get_length(&numitems);<br />
for (int i=0;i < numitems;i++)<br />
{<br />
MSXML2::IXMLDOMNodePtr item ;<br />
items->get_item(i, &item);<br />
_variant_t sz1 = item->attributes->getNamedItem("Mode")->GetnodeValue();<br />
_variant_t sz2 = item->attributes->getNamedItem("Keyer")->GetnodeValue();<br />
}<br />
printf("Found %f Records\n", numitems);<br />
}<br />
|
|
|
|
|
Look at the CXmlNodeListWrapper class, that is what you need,
also user CXmlNodeWrapper::FindNodes , wich returns a node list.
i.e : CXmlNodeListWrapper list(xmlNode.FindNodes("//Z:Row[@Type='sometype']");
Creative minds - create creative creations!
|
|
|
|
|
Hi again!
I might be off here but why does almost every function return a BOOL?
In the msxml3.tli (created by VC.NET from the #import) every call has a:
if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));
which throws a _com_error.
So dosent all functions either return TRUE or throw an exception? Or am I missing something elementary (I am not an expert in COM)?
/Aldus
P.s.
Good work with the XML wrapper!
D.s.
|
|
|
|
|
Hi!
I get a link error while compileing the wrapper. Do I need to include some .lib? Does the wrapper work in my MFC project or will it only work with an ATL project? I use VS.NET2003 as compiler.
XmlNodeWrapper.obj : error LNK2019: unresolved external symbol "wchar_t * __stdcall _com_util::ConvertStringToBSTR(char const *)" (?ConvertStringToBSTR@_com_util@@YGPA_WPBD@Z) referenced in function "public: __thiscall _bstr_t::Data_t::Data_t(char const *)" (??0Data_t@_bstr_t@@QAE@PBD@Z)
XmlNodeWrapper.obj : error LNK2019: unresolved external symbol "char * __stdcall _com_util::ConvertBSTRToString(wchar_t *)" (?ConvertBSTRToString@_com_util@@YGPADPA_W@Z) referenced in function "public: char const * __thiscall _bstr_t::Data_t::GetString(void)const " (?GetString@Data_t@_bstr_t@@QBEPBDXZ)
Best regards
Aldus
|
|
|
|
|
Hi again!
I used the wrapper in a regular DLL with MFC statically linked, but now I think I have solved it myself:
I changed the setting in "C/C++ -> Language -> Treat wchar_t as Built-In Type" to "No"
and now it links ok.
Best regards
Aldus
|
|
|
|
|
Yes the wrapper uses MFC so you must specify using MFC in the project properties.
Creative minds - create creative creations!
|
|
|
|
|
I have tested the classes to use them in my application and I have realized that they only work for Doc/View projects (at least in VS2003), not in dialog or console based apps.
In non Doc/View apps it fails in:
<br />
CXmlDocumentWrapper::CXmlDocumentWrapper()<br />
{<br />
m_xmldoc.CreateInstance(MSXML2::CLSID_DOMDocument);<br />
}<br />
It always returns NULL.
How can I modify the classes to make them work in a Windows Service or a console app?
Is it possible or it depends on the dll?
|
|
|
|
|
Make sure to call CoInitialize
Creative minds - create creative creations!
|
|
|
|
|
|
hi alex
i think i may have discovered a memory issue relating to releasing the underlying interfaces that you may want to document.
when initializing an implict _com_ptr_t (as happens everywhere) with an interface pointer, _com_ptr_t constructor AddRef 's as you would expect.
The problem occurs when the wrapper functions call Detach internally on those _com_ptr_t because now the interface has an extra AddRef on it and unless I call Release explicitly on the interface it will not get released until the application ends.
ie.
CXmlDocumentWrapper doc;<br />
<br />
:<br />
<br />
CXmlNodeWrapper node(doc.AsNode());<br />
<br />
:
will leave the document interface hanging around. what's needed is an extra Release like this:
CXmlDocumentWrapper doc;<br />
<br />
:<br />
<br />
IXMLDOMNode* pNode = pDoc->AsNode(); <br />
CXmlNodeWrapper node(pNode);<br />
<br />
:<br />
<br />
pNode->Release();
note: i'm working with large xml files (500k+) where the memory increase is very significant. with the changes i've suggested, the 'leak' goes away.
rgds
.dan.g.
AbstractSpoon Software
|
|
|
|
|
Yes you aer right!!!
Also i beleave that just removing Detach() from the function will do the trick.
The returned _com_ptr will be cast to pointer thus returning the interface and then destroyed thus releasing the interface.
i.e.
Instead of:
MSXML2::IXMLDOMNode* CXmlDocumentWrapper::AsNode()
{
if (!IsValid())
return NULL;
return m_xmldoc->GetdocumentElement().Detach();
}
change to:
MSXML2::IXMLDOMNode* CXmlDocumentWrapper::AsNode()
{
if (!IsValid())
return NULL;
return m_xmldoc->GetdocumentElement();
}
Creative minds - create creative creations!
|
|
|
|
|
thanks. i'll try your suggestion because keeping such details hidden is vastly preferable to my solution of always having to remember.
however, is there not a risk that when the _com_ptr goes out of scope it will release the interface and COM will blitz it before it can be used.
.dan.g.
AbstractSpoon Software
|
|
|
|
|
The memory leak issue is finaly resolved!
The problem is that several functions in the wrapper returns an interface pointer, when in fact they should return com wrapper i.e. : xxxPtr
The only functions that should return raw pointers are Interface() and Detach()
Until I update the article with the required changes you can solve the problem by replacing ALL
IXMLDOMNode* with IXMLDOMNodePtr except in Inetrface() and Detach() function
same goes for IXMLDOMDocument and IXMLDOMNodeList
Of course there will be some errors on compilation, to resolve the errors:
In the insert function like insert before use: _variant_t(refNode.GetInterfacePtr())
For example:
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::InsertBefore(MSXML2::IXMLDOMNodePtr refNode, LPCTSTR nodeName)<br />
{<br />
MSXML2::IXMLDOMDocumentPtr xmlDocument = m_xmlnode->GetownerDocument();<br />
if (xmlDocument)<br />
{<br />
MSXML2::IXMLDOMNodePtr newNode = xmlDocument->createNode(_variant_t((short)MSXML2::NODE_ELEMENT),nodeName,"");<br />
newNode = m_xmlnode->insertBefore(newNode,_variant_t(refNode.GetInterfacePtr()));<br />
return newNode;<br />
}<br />
return NULL;<br />
}
Creative minds - create creative creations!
|
|
|
|
|
Ok, the only bug to be fixed is your signature.. my version is :
Creative creatures - create creative creations!
Thanks for the wrapper class!
|
|
|
|
|
Hi dear, thanks for this usefull code.
I had memory allocation problem. My application it's a relatime application 24h/7 day active, there a thread thata create an xml statistic file. After some one day or 2 the application has an exception for out of memory. I create a test platform and increase the frequency of creation of statisti and after 1 hour i have the same proble.
I put the code FROM IXMLDOMNode* TO IXMLDOMNodePtr but the proble is the same. I create a big file about 120kbyte.
I put some code for example
m_xmlDoc = new CXmlDocumentWrapper();
m_xmlDoc->Load(_T("Statistic.xml"));
if(m_xmlDoc->IsValid())
{
CXmlNodeWrapper pNode(m_xmlDoc->AsNode(),TRUE);
if(pNode.IsValid())
{
for (int i = 0; i < pNode.NumNodes(); i++)
{
CXmlNodeWrapper node(pNode.GetNode(i),TRUE);
CString tmpVal = node.Name();
if(tmpVal == _T("CONFIGURATION"))
{
CXmlNodeWrapper childNodeConf(node.InsertNode(node.NumNodes(),"SourceName"),TRUE);
childNodeConf.SetText(strFileName);
childNodeConf = (node.InsertNode(node.NumNodes(),"Site"));
childNodeConf.SetText(_T("01"));
.......
.......
}
}
}
thanks
|
|
|
|
|
Dan, gospodin Hazanov's solution worked perfectly for me as it was,
Many, many thanks to him to share with us his xml in native(“unmanaged”) c++ experience
As suggested by your discussion, I modified the XmlNodeWrapper.cpp/.h files.
The project compiles and continues to work perfectly... (?!?) No leaks, nothing
Can you please say us if it changed something :
(To save Chris's server, I compressed a little the texts + Apologizes..)
===================== XmlNodeWrapper.h ===================
#pragma once
#import "MSXML3.dll" named_guids
using namespace MSXML2;
class CXmlNodeWrapper
{
public:
CString NodeType();
CString GetAttribVal(int index);
CString GetAttribName(int index);
int NumAttributes();
void ReplaceNode(MSXML2::IXMLDOMNodePtr pOldNode,MSXML2::IXMLDOMNodePtr pNewNode);
CString GetText();
void SetText(LPCTSTR text);
MSXML2::IXMLDOMNodePtr InsertAfter(MSXML2::IXMLDOMNodePtr refNode, MSXML2::IXMLDOMNodePtr pNode);
CString Name();
MSXML2::IXMLDOMNodeListPtr FindNodes(LPCTSTR searchStr);
MSXML2::IXMLDOMNodePtr Parent();
void RemoveNodes(LPCTSTR searchStr);
MSXML2::IXMLDOMNodePtr InsertAfter(MSXML2::IXMLDOMNodePtr refNode, LPCTSTR nodeName);
MSXML2::IXMLDOMNodePtr InsertBefore(MSXML2::IXMLDOMNodePtr refNode, LPCTSTR nodeName);
MSXML2::IXMLDOMNode* Interface();
MSXML2::IXMLDOMDocumentPtr ParentDocument();
CString GetXML();
MSXML2::IXMLDOMNodePtr RemoveNode(MSXML2::IXMLDOMNodePtr pNode);
MSXML2::IXMLDOMNodePtr InsertNode(int index,LPCTSTR nodeName);
MSXML2::IXMLDOMNodePtr InsertNode(int index,MSXML2::IXMLDOMNodePtr pNode);
long NumNodes();
MSXML2::IXMLDOMNode* Detach();
MSXML2::IXMLDOMNodePtr GetNode(LPCTSTR nodeName);
MSXML2::IXMLDOMNodePtr GetNode(int nodeIndex);
MSXML2::IXMLDOMNodePtr FindNode(LPCTSTR searchString);
MSXML2::IXMLDOMNodePtr GetPrevSibling();
MSXML2::IXMLDOMNodePtr GetNextSibling();
void SetValue(LPCTSTR valueName,LPCTSTR value);
void SetValue(LPCTSTR valueName,int value);
void SetValue(LPCTSTR valueName,short value);
void SetValue(LPCTSTR valueName,double value);
void SetValue(LPCTSTR valueName,float value);
void SetValue(LPCTSTR valueName,bool value);
BOOL IsValid();
CString GetValue(LPCTSTR valueName);
CXmlNodeWrapper();
CXmlNodeWrapper(MSXML2::IXMLDOMNodePtr pNode,BOOL bAutoRelease = TRUE);
void operator=(MSXML2::IXMLDOMNodePtr pNode);
virtual ~CXmlNodeWrapper();
private:
BOOL m_bAutoRelease;
MSXML2::IXMLDOMNodePtr m_xmlnode;
};
class CXmlDocumentWrapper
{
public:
CString GetUrl();
CString GetXML();
BOOL IsValid();
BOOL Load(LPCTSTR path);
BOOL LoadXML(LPCTSTR xml);
BOOL Save(LPCTSTR path = "");
MSXML2::IXMLDOMDocument* Detach();
MSXML2::IXMLDOMDocumentPtr Clone();
CXmlDocumentWrapper();
CXmlDocumentWrapper(MSXML2::IXMLDOMDocumentPtr pDoc);
MSXML2::IXMLDOMNodePtr AsNode();
virtual ~CXmlDocumentWrapper();
private:
MSXML2::IXMLDOMDocumentPtr m_xmldoc;
};
class CXmlNodeListWrapper
{
public:
MSXML2::IXMLDOMDocumentPtr AsDocument();
MSXML2::IXMLDOMNodePtr Node(int index);
void Start();
MSXML2::IXMLDOMNodePtr Next();
BOOL IsValid();
int Count();
CXmlNodeListWrapper();
CXmlNodeListWrapper(MSXML2::IXMLDOMNodeListPtr pList);
void operator=(MSXML2::IXMLDOMNodeListPtr pList);
virtual ~CXmlNodeListWrapper();
private:
MSXML2::IXMLDOMNodeListPtr m_xmlnodelist;
};
===================== XmlNodeWrapper.cpp =================
#include "stdafx.h"
#include "XmlNodeWrapper.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CXmlNodeWrapper::CXmlNodeWrapper() {}
CXmlNodeWrapper::CXmlNodeWrapper(MSXML2::IXMLDOMNodePtr pNode,BOOL bAutoRelease) {
m_xmlnode = pNode;
m_bAutoRelease = bAutoRelease;
}
void CXmlNodeWrapper::operator=(MSXML2::IXMLDOMNodePtr pNode) {
if (IsValid())
m_xmlnode.Release();
m_xmlnode = pNode;
}
CXmlNodeWrapper::~CXmlNodeWrapper() {
if (!m_bAutoRelease)
m_xmlnode.Detach();
}
CString CXmlNodeWrapper::GetValue(LPCTSTR valueName) {
if (!IsValid())
return "";
MSXML2::IXMLDOMNodePtr attribute = m_xmlnode->Getattributes()->getNamedItem(valueName);
if (attribute) {
return (LPCSTR)attribute->Gettext();
}
return "";
}
BOOL CXmlNodeWrapper::IsValid() {
if (m_xmlnode == NULL)
return FALSE;
if (m_xmlnode.GetInterfacePtr() == NULL)
return FALSE;
return TRUE;
}
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::GetPrevSibling() {
if (!IsValid())
return NULL;
return m_xmlnode->GetpreviousSibling(); //.Detach();
}
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::GetNextSibling() {
if (!IsValid())
return NULL;
return m_xmlnode->GetnextSibling(); //.Detach();
}
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::GetNode(LPCTSTR nodeName) {
if (!IsValid())
return NULL;
try{
return m_xmlnode->selectSingleNode(nodeName); //.Detach();
}
catch (_com_error e) {
CString err = e.ErrorMessage();
}
return NULL;
}
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::GetNode(int nodeIndex) {
if (!IsValid())
return NULL;
return m_xmlnode->GetchildNodes()->Getitem(nodeIndex); //.Detach();
}
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::FindNode(LPCTSTR searchString) {
if (!IsValid())
return NULL;
try{
return m_xmlnode->selectSingleNode(searchString); //.Detach();
}
catch (_com_error e) {
CString err = e.ErrorMessage();
}
return NULL;
}
MSXML2::IXMLDOMNode* CXmlNodeWrapper::Detach() {
if (IsValid()) {
return m_xmlnode.Detach();
}
else
return NULL;
}
long CXmlNodeWrapper::NumNodes() {
if (IsValid()) {
return m_xmlnode->GetchildNodes()->Getlength();
}
else
return 0;
}
void CXmlNodeWrapper::SetValue(LPCTSTR valueName,LPCTSTR value) {
MSXML2::IXMLDOMDocumentPtr xmlDocument = m_xmlnode->GetownerDocument();
if (xmlDocument) {
MSXML2::IXMLDOMNamedNodeMapPtr attributes = m_xmlnode->Getattributes();
if (attributes) {
MSXML2::IXMLDOMAttributePtr attribute = xmlDocument->createAttribute(valueName);
if (attribute) {
attribute->Puttext(value);
attributes->setNamedItem(attribute);
}
}
}
}
void CXmlNodeWrapper::SetValue(LPCTSTR valueName,int value) {
CString str;
str.Format("%ld",value);
SetValue(valueName,str);
}
void CXmlNodeWrapper::SetValue(LPCTSTR valueName,short value) {
CString str;
str.Format("%hd",value);
SetValue(valueName,str);
}
void CXmlNodeWrapper::SetValue(LPCTSTR valueName,double value) {
CString str;
str.Format("%f",value);
SetValue(valueName,str);
}
void CXmlNodeWrapper::SetValue(LPCTSTR valueName,float value) {
CString str;
str.Format("%f",value);
SetValue(valueName,str);
}
void CXmlNodeWrapper::SetValue(LPCTSTR valueName,bool value) {
CString str;
if (value)
str = "True";
else
str = "False";
SetValue(valueName,str);
}
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::InsertNode(int index,LPCTSTR nodeName) {
MSXML2::IXMLDOMDocumentPtr xmlDocument = m_xmlnode->GetownerDocument();
if (xmlDocument) {
MSXML2::IXMLDOMNodePtr newNode = xmlDocument->createNode(_variant_t((short)MSXML2::NODE_ELEMENT),nodeName,"");
MSXML2::IXMLDOMNodePtr refNode = GetNode(index);
if (refNode)
// newNode = m_xmlnode->insertBefore(newNode.Detach(),refNode);
newNode = m_xmlnode->insertBefore(newNode,(const _variant_t &)refNode);
else
newNode = m_xmlnode->appendChild(newNode); //.Detach());
return newNode; //.Detach();
}
return NULL;
}
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::InsertNode(int index,MSXML2::IXMLDOMNodePtr pNode) {
MSXML2::IXMLDOMNodePtr newNode = pNode->cloneNode(VARIANT_TRUE);
if (newNode) {
MSXML2::IXMLDOMNodePtr refNode = GetNode(index);
if (refNode)
newNode = m_xmlnode->insertBefore(newNode,(const _variant_t &)refNode);
else
newNode = m_xmlnode->appendChild(newNode); //.Detach());
return newNode; //.Detach();
}
else
return NULL;
}
CString CXmlNodeWrapper::GetXML() {
if (IsValid())
return (LPCSTR)m_xmlnode->Getxml();
else
return "";
}
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::RemoveNode(MSXML2::IXMLDOMNodePtr pNode) {
if (!IsValid())
return NULL;
return m_xmlnode->removeChild(pNode); //.Detach();
}
/* ************************************************ (vive CodeProject! ... etc..) */
CXmlDocumentWrapper::CXmlDocumentWrapper() {
m_xmldoc.CreateInstance(MSXML2::CLSID_DOMDocument);
}
CXmlDocumentWrapper::CXmlDocumentWrapper(MSXML2::IXMLDOMDocumentPtr pDoc) {
m_xmldoc = pDoc;
}
CXmlDocumentWrapper::~CXmlDocumentWrapper() {
}
BOOL CXmlDocumentWrapper::IsValid() {
if (m_xmldoc == NULL)
return FALSE;
if (m_xmldoc.GetInterfacePtr() == NULL)
return FALSE;
return TRUE;
}
MSXML2::IXMLDOMDocument* CXmlDocumentWrapper::Detach() {
if (!IsValid())
return NULL;
return m_xmldoc.Detach();
}
MSXML2::IXMLDOMDocumentPtr CXmlDocumentWrapper::Clone() {
if (!IsValid())
return NULL;
MSXML2::IXMLDOMDocumentPtr xmldoc;
xmldoc.CreateInstance(MSXML2::CLSID_DOMDocument);
_variant_t v(xmldoc.GetInterfacePtr());
m_xmldoc->save(v);
return xmldoc; //.Detach();
}
BOOL CXmlDocumentWrapper::Load(LPCTSTR path) {
if (!IsValid())
return FALSE;
_variant_t v(path);
m_xmldoc->put_async(VARIANT_FALSE);
VARIANT_BOOL success = m_xmldoc->load(v);
if (success == VARIANT_TRUE)
return TRUE;
else
return FALSE;
}
BOOL CXmlDocumentWrapper::LoadXML(LPCTSTR xml) {
if (!IsValid())
return FALSE;
VARIANT_BOOL success = m_xmldoc->loadXML(xml);
if (success == VARIANT_TRUE)
return TRUE;
else
return FALSE;
}
BOOL CXmlDocumentWrapper::Save(LPCTSTR path) {
try
{
if (!IsValid())
return FALSE;
CString szPath(path);
if (szPath == "") {
_bstr_t curPath = m_xmldoc->Geturl();
szPath = (LPSTR)curPath;
}
_variant_t v(szPath);
if (FAILED(m_xmldoc->save(v)))
return FALSE;
else
return TRUE;
}
catch(...) {
return FALSE;
}
}
MSXML2::IXMLDOMNodePtr CXmlDocumentWrapper::AsNode() {
if (!IsValid())
return NULL;
// plante ! : return m_xmldoc->GetdocumentElement(); //.Detach(); modif ... sans Detach
return m_xmldoc->GetdocumentElement(); //.Detach();
}
CString CXmlDocumentWrapper::GetXML() {
if (IsValid())
return (LPCSTR)m_xmldoc->Getxml();
else
return "";
}
CString CXmlDocumentWrapper::GetUrl() {
return (LPSTR)m_xmldoc->Geturl();
}
MSXML2::IXMLDOMDocumentPtr CXmlNodeWrapper::ParentDocument() {
return m_xmlnode->GetownerDocument(); //.Detach();
}
MSXML2::IXMLDOMNode* CXmlNodeWrapper::Interface() {
if (IsValid())
return m_xmlnode;
return NULL;
}
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::InsertBefore(MSXML2::IXMLDOMNodePtr refNode, LPCTSTR nodeName) {
MSXML2::IXMLDOMDocumentPtr xmlDocument = m_xmlnode->GetownerDocument();
if (xmlDocument) {
MSXML2::IXMLDOMNodePtr newNode = xmlDocument->createNode(_variant_t((short)MSXML2::NODE_ELEMENT),nodeName,"");
newNode = m_xmlnode->insertBefore(newNode,_variant_t(refNode.GetInterfacePtr()));
return newNode;
}
return NULL;
}
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::InsertAfter(MSXML2::IXMLDOMNodePtr refNode, LPCTSTR nodeName) {
MSXML2::IXMLDOMDocumentPtr xmlDocument = m_xmlnode->GetownerDocument();
if (xmlDocument) {
MSXML2::IXMLDOMNodePtr newNode = xmlDocument->createNode(_variant_t((short)MSXML2::NODE_ELEMENT),nodeName,"");
MSXML2::IXMLDOMNodePtr nextNode = refNode->GetnextSibling();
if (nextNode.GetInterfacePtr() != NULL)
newNode = m_xmlnode->insertBefore(newNode,_variant_t(nextNode.GetInterfacePtr()));
else
newNode = m_xmlnode->appendChild(newNode);
return newNode;
}
return NULL;
}
void CXmlNodeWrapper::RemoveNodes(LPCTSTR searchStr) {
if (!IsValid())
return;
MSXML2::IXMLDOMNodeListPtr nodeList = m_xmlnode->selectNodes(searchStr);
for (int i = 0; i < nodeList->Getlength(); i++) {
try
{
MSXML2::IXMLDOMNodePtr pNode = nodeList->Getitem(i); //.Detach();
pNode->GetparentNode()->removeChild(pNode);
}
catch (_com_error er) {
AfxMessageBox(er.ErrorMessage());
}
}
}
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::Parent() {
if (IsValid())
return m_xmlnode->GetparentNode(); //.Detach();
return NULL;
}
CXmlNodeListWrapper::CXmlNodeListWrapper() {
}
CXmlNodeListWrapper::CXmlNodeListWrapper(MSXML2::IXMLDOMNodeListPtr pList) {
m_xmlnodelist = pList;
}
void CXmlNodeListWrapper::operator=(MSXML2::IXMLDOMNodeListPtr pList) {
if (IsValid())
m_xmlnodelist.Release();
m_xmlnodelist = pList;
}
CXmlNodeListWrapper::~CXmlNodeListWrapper() {
}
int CXmlNodeListWrapper::Count() {
if (IsValid())
return m_xmlnodelist->Getlength();
else
return 0;
}
BOOL CXmlNodeListWrapper::IsValid() {
if (m_xmlnodelist == NULL)
return FALSE;
if (m_xmlnodelist.GetInterfacePtr() == NULL)
return FALSE;
return TRUE;
}
MSXML2::IXMLDOMNodePtr CXmlNodeListWrapper::Next() {
if (IsValid())
return m_xmlnodelist->nextNode(); //.Detach();
else
return NULL;
}
void CXmlNodeListWrapper::Start() {
if (IsValid())
m_xmlnodelist->reset();
}
MSXML2::IXMLDOMNodePtr CXmlNodeListWrapper::Node(int index) {
if (IsValid())
return m_xmlnodelist->Getitem(index); //.Detach();
else
return NULL;
}
MSXML2::IXMLDOMDocumentPtr CXmlNodeListWrapper::AsDocument() {
if (IsValid()) {
CXmlDocumentWrapper doc;
doc.LoadXML("<NodeList></NodeList>");
CXmlNodeWrapper root(doc.AsNode());
for (int i = 0; i < m_xmlnodelist->Getlength(); i++) {
root.InsertNode(root.NumNodes(),m_xmlnodelist->Getitem(i)->cloneNode(VARIANT_TRUE));
}
return doc.Detach();
}
else
return NULL;
}
MSXML2::IXMLDOMNodeListPtr CXmlNodeWrapper::FindNodes(LPCTSTR searchStr) {
if(IsValid()) {
try{
return m_xmlnode->selectNodes(searchStr); //.Detach();
}
catch (_com_error e) {
CString err = e.ErrorMessage();
return NULL;
}
}
else
return NULL;
}
CString CXmlNodeWrapper::Name() {
if (IsValid())
return (LPCSTR)m_xmlnode->GetbaseName();
return "";
}
MSXML2::IXMLDOMNodePtr CXmlNodeWrapper::InsertAfter(MSXML2::IXMLDOMNodePtr refNode, MSXML2::IXMLDOMNodePtr pNode) {
MSXML2::IXMLDOMNodePtr nextNode = refNode->GetnextSibling();
MSXML2::IXMLDOMNodePtr newNode;
if (nextNode.GetInterfacePtr() != NULL)
newNode = m_xmlnode->insertBefore(pNode,_variant_t(nextNode.GetInterfacePtr()));
else
newNode = m_xmlnode->appendChild(pNode);
return newNode;
}
void CXmlNodeWrapper::SetText(LPCTSTR text) {
if (IsValid())
m_xmlnode->Puttext(text);
}
CString CXmlNodeWrapper::GetText() {
if (IsValid())
return (LPCSTR)m_xmlnode->Gettext();
else
return "";
}
void CXmlNodeWrapper::ReplaceNode(MSXML2::IXMLDOMNodePtr pOldNode, MSXML2::IXMLDOMNodePtr pNewNode) {
if (IsValid()) {
m_xmlnode->replaceChild(pNewNode,pOldNode);
}
}
int CXmlNodeWrapper::NumAttributes() {
if (IsValid()) {
MSXML2::IXMLDOMNamedNodeMapPtr attribs = m_xmlnode->Getattributes();
if (attribs)
return attribs->Getlength();
}
return 0;
}
CString CXmlNodeWrapper::GetAttribName(int index) {
if (IsValid()) {
MSXML2::IXMLDOMNamedNodeMapPtr attribs = m_xmlnode->Getattributes();
if (attribs) {
MSXML2::IXMLDOMAttributePtr attrib = attribs->Getitem(index);
if (attrib)
return (LPCSTR)attrib->Getname();
}
}
return "";
}
CString CXmlNodeWrapper::GetAttribVal(int index) {
if (IsValid()) {
MSXML2::IXMLDOMNamedNodeMapPtr attribs = m_xmlnode->Getattributes();
if (attribs) {
MSXML2::IXMLDOMAttributePtr attrib = attribs->Getitem(index);
if (attrib)
return (LPCSTR)attrib->Gettext();
}
}
return "";
}
CString CXmlNodeWrapper::NodeType() {
if (IsValid())
return (LPCSTR)m_xmlnode->GetnodeTypeString();
return "";
}
|
|
|
|
|
both alex's and my solution were essentially the same, although i haven't tried alex's because of a number of other additions that i had already made to his work. as a result i'm unable to say whether what you've posted here is correct or not. my experiance though is that if it works functionally and there are no apparent leaks (or increases in the working memory as reported by TaskMgr.exe) then its probably okay.
i will probably merge alex's fix into my version as soon as my current software is released so that i can ensure that it works as expected before i release it on unsuspecting users.
.dan.g.
AbstractSpoon Software
|
|
|
|
|
hi alex,
can i ask why the destructors of the wrappers do not Release the underlying COM pointers? i would have thought that unless the user explicitly calls Detach or m_bAutoDelete is FALSE then the COM pointers need be cleaned up.
your thoughts?
.dan.g.
AbstractSpoon Software
|
|
|
|
|