MFC下XML遍历同名节点(Node)
主要还是弄清Nodelist和Node的关系。
1 #include <iostream>
2 #include <tchar.h>
3
4 #import <msxml3.dll>
5
6 int _tmain(int argc, _TCHAR* argv[])
7 {
8 CoInitialize(NULL);
9 //读取XML
10 MSXML2::IXMLDOMDocumentPtr spXMLDoc;
11 spXMLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
12 spXMLDoc->load(L"config.xml");
13 MSXML2::IXMLDOMElementPtr spRoot = spXMLDoc->documentElement; //根节点
14
15 //写入XML
16 MSXML2::IXMLDOMNodePtr spNewNode = spRoot->selectSingleNode(L"/Win-DMS/SharedFolders")->appendChild(
17 spXMLDoc->createNode(_variant_t(NODE_ELEMENT), L"Folder", L"")
18 );
19 spNewNode->text = L"D:\\123456\\";
20 spXMLDoc->save(_variant_t(L"config.xml"));
21
22 MSXML2::IXMLDOMNodeListPtr nolistptr = NULL;
23 spNewNode->get_childNodes(&nolistptr);
24
25 for (int i =0; i <nolistptr->Getlength(); i++)
26 {
27 MSXML2::IXMLDOMNodePtr nodeptr = NULL;
28 nodeptr = nolistptr->Getitem(i);
29 std::cout << "\tnodeValue: " << _bstr_t(nodeptr->nodeValue);
30 std::cout << std::endl;
31 }
32
33 spNewNode.Release();
34 //spNodeList.Release();
35 spRoot.Release();
36 spXMLDoc.Release();
37 CoUninitialize();
38
39 system("pause");
40 return 0;
41 }
判断是否有相同的元素,如果没有就加入到配置文件中去:
1 MSXML2::IXMLDOMDocumentPtr spXMLDoc;
2 spXMLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
3 spXMLDoc->load(L"config.xml");
4 MSXML2::IXMLDOMElementPtr spRoot = spXMLDoc->documentElement;
5 MSXML2::IXMLDOMNodePtr spShareNode = spRoot->selectSingleNode(L"/Win-DMS/SharedFolders");
6 MSXML2::IXMLDOMNodeListPtr FolderListPtr = NULL;
7 spShareNode->get_childNodes(&FolderListPtr);
8 MSXML2::IXMLDOMNodePtr FolderNodePtr = NULL;
9 long len = FolderListPtr->Getlength();
10 for (int i =0; i <len; i++)
11 {
12 FolderNodePtr = FolderListPtr->Getitem(i);
13 BSTR text = FolderNodePtr->Gettext();
14 if(!lstrcmp((LPCWSTR)text ,szPath))
15 {
16 isSaved = TRUE;
17 break;
18 //AfxMessageBox(L"该目录已经在列表中……");
19 }
20 }
21 if(isSaved == FALSE)
22 {
23 m_OwnerListBox->Add(szPath, AfxGetApp()->LoadIcon(IDI_FOLDER));
24 //读取XML
25 MSXML2::IXMLDOMNodePtr spNewNode = spRoot->selectSingleNode(L"/Win-DMS/SharedFolders")->appendChild(
26 spXMLDoc->createNode(_variant_t(NODE_ELEMENT), L"Folder", L"")
27 );
28 spNewNode->text = szPath;
29 spXMLDoc->save(_variant_t(L"config.xml"));
30 }