MFC遍历XML同名节点

标签: XML mfc
发布时间: 2012/2/22 17:19:54

遍历XML文件的关键问题就是如何区分nodelist和node,以及怎么判断是否有相同元素等.

#include <iostream>
#include <tchar.h>

#import <msxml3.dll>

int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL);
//读取XML
MSXML2::IXMLDOMDocumentPtr spXMLDoc;
spXMLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
spXMLDoc->load(L"config.xml");
MSXML2::IXMLDOMElementPtr spRoot = spXMLDoc->documentElement; //根节点

//写入XML
MSXML2::IXMLDOMNodePtr spNewNode = spRoot->selectSingleNode(L"/Win-DMS/SharedFolders")->appendChild(
spXMLDoc->createNode(_variant_t(NODE_ELEMENT), L"Folder", L"")
); 
spNewNode->text = L"D:\\123456\\";
spXMLDoc->save(_variant_t(L"config.xml"));

MSXML2::IXMLDOMNodeListPtr nolistptr = NULL;
spNewNode->get_childNodes(&nolistptr);

for (int i =0; i <nolistptr->Getlength(); i++)
{
    MSXML2::IXMLDOMNodePtr nodeptr = NULL;
    nodeptr = nolistptr->Getitem(i);
    std::cout << "\tnodeValue: " << _bstr_t(nodeptr->nodeValue);
    std::cout << std::endl;
}

spNewNode.Release();
//spNodeList.Release();
spRoot.Release();
spXMLDoc.Release();
CoUninitialize();

system("pause");
return 0;
}

判断xml是否有相同的节点

MSXML2::IXMLDOMDocumentPtr spXMLDoc;
spXMLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
spXMLDoc->load(L"config.xml");
MSXML2::IXMLDOMElementPtr spRoot = spXMLDoc->documentElement; 
MSXML2::IXMLDOMNodePtr spShareNode = spRoot->selectSingleNode(L"/Win-DMS/SharedFolders");
MSXML2::IXMLDOMNodeListPtr FolderListPtr = NULL;
spShareNode->get_childNodes(&FolderListPtr);
MSXML2::IXMLDOMNodePtr FolderNodePtr = NULL;
long len = FolderListPtr->Getlength();
for (int i =0; i <len; i++)
{
    FolderNodePtr = FolderListPtr->Getitem(i);
    BSTR text = FolderNodePtr->Gettext();
    if(!lstrcmp((LPCWSTR)text ,szPath))
    {
        isSaved = TRUE;
        break;
        //AfxMessageBox(L"该目录已经在列表中……");    
    }
}
if(isSaved == FALSE)
{
  m_OwnerListBox->Add(szPath,  AfxGetApp()->LoadIcon(IDI_FOLDER));
  //读取XML
  MSXML2::IXMLDOMNodePtr spNewNode = spRoot->selectSingleNode(L"/Win-DMS/SharedFolders")->appendChild(
      spXMLDoc->createNode(_variant_t(NODE_ELEMENT), L"Folder", L"")
      ); 
  spNewNode->text = szPath;
  spXMLDoc->save(_variant_t(L"config.xml"));
}

赞助商