一,建立一個基于對話框的程序,工程名為xml;
二, 初始化OLE. BOOL CXmlApp::InitInstance() { AfxOleInit(); ……. } 三, 在對話框中增加一個按鈕,ID為IDC_CREATE,我們在這個按鈕的響應函數(shù)中生成一個xml文件. void CXmlDlg::OnCreate() { MSXML2::IXMLDOMDocumentPtr pDoc; MSXML2::IXMLDOMElementPtr xmlRoot ; //創(chuàng)建DOMDocument對象 HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30)); if(!SUCCEEDED(hr)) { MessageBox("無法創(chuàng)建DOMDocument對象,請檢查是否安裝了MS XML Parser 運行庫!"); } //根節(jié)點的名稱為china pDoc->raw_createElement((_bstr_t)(char*)"china", &xmlRoot); pDoc->raw_appendChild(xmlRoot, NULL); MSXML2::IXMLDOMElementPtr childNode ; pDoc->raw_createElement((_bstr_t)(char*)"City", &childNode); childNode->Puttext("WuHan");//節(jié)點值 childNode->setAttribute("population","8,000,000");//屬性名,屬性值 childNode->setAttribute("area","10000"); xmlRoot->appendChild(childNode); pDoc->raw_createElement((_bstr_t)(char*)"City", &childNode); childNode->Puttext("ShangHai"); childNode->setAttribute("population","12,000,000"); childNode->setAttribute("area","12000"); xmlRoot->appendChild(childNode); //保存到文件 //如果不存在就建立,存在就覆蓋 pDoc->save("f:\\he.xml"); } 不要忘了#import "msxml4.dll" //引入類型庫 四, 再增加一個按鈕,ID為IDC_GET,在這個按鈕的響應函數(shù)中讀取xml文件. void CXmlDlg::OnGet() { //創(chuàng)建DOMDocument對象 MSXML2::IXMLDOMDocumentPtr pDoc; HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30)); if(!SUCCEEDED(hr)) { MessageBox("無法創(chuàng)建DOMDocument對象,請檢查是否安裝了MS XML Parser 運行庫!"); } //加載文件 pDoc->load("f:\\he.xml"); //在樹中查找名為City的節(jié)點,"http://"表示在任意一層查找 MSXML2::IXMLDOMElementPtr childNode ; childNode = (MSXML2::IXMLDOMElementPtr)(pDoc->selectSingleNode("http://City")); //得到節(jié)點類型 MSXML2::DOMNodeType nodeType; childNode->get_nodeType(&nodeType); //節(jié)點名稱 BSTR var; CString name; childNode->get_nodeName(&var); name = (char*)(_bstr_t)var; //節(jié)點值 VARIANT varVal; childNode->get_nodeTypedValue(&varVal); CString strValue = (char*)(_bstr_t)varVal; //節(jié)點屬性,放在鏈表中 MSXML2::IXMLDOMNamedNodeMapPtr pAttrs = NULL; MSXML2::IXMLDOMNodePtr pAttrItem; childNode->get_attributes(&pAttrs); long nCount ; pAttrs->get_length(&nCount); for(int i = 0 ; i < nCount ; i++) { pAttrs->get_item(i,&pAttrItem); //我們可以通過函數(shù)get_nodeName,get_nodeTypedValue得到屬性名和屬性值 //也可以直接得到 CString strAttrName = (char*)(_bstr_t)pAttrItem->nodeName; CString strAttrValue = (char*)(_bstr_t)pAttrItem->nodeTypedValue; } } |
|
來自: yiherainbow > 《我的圖書館》