现在经常会对XML文件进行操作,怎么在MFC下去读和解析XML文件呢?直接上代码:
首先得等在stdafx.h中加入这句,以引入MSXML命名空间
#import <msxml3.dll> named_guids using namespace MSXML2;
然后再要使用的类的头文件加入:
MSXML2::IXMLDOMDocument2Ptrm_plDomDocument;
- MSXML2::IXMLDOMElementPtrm_pDocRoot;
然后在初始化函数中加入对XML COM的初始化:
- ::CoInitialize(NULL);
- HRESULThr=m_plDomDocument.CreateInstance(MSXML2::CLSID_DOMDocument);
-
- if(FAILED(hr))
- {
- _com_errorer(hr);
- AfxMessageBox(er.ErrorMessage());
- EndDialog(1);
- }
接着是具体的函数:
voidCDemoDlg::OnBnClickedButtonOpenxml()
- //atfirst,weshouldclearm_strXML'scontentstoshownewdata
- m_strXMLData="";
-
- CFileDialogfileDlg(TRUE);
- if(IDOK==fileDlg.DoModal())
- m_strXMLPath=fileDlg.GetPathName();
- m_strXMLContents="Emptydocument";
-
- UpdateData(FALSE);
- //SpecifyXMLfilename
- CStringstrFileName=m_strXMLPath;
- //ConvertXMLfilenamestringtosomethingCOMcanhandle
- _bstr_tbstrFileName;
- bstrFileName=strFileName.AllocSysString();
- //CalltheIXMLDOMDocumentPtr'sloadfunctiontoloadXMLfile
- variant_tvResult;
- vResult=m_plDomDocument->load(bstrFileName);
- if(((bool)vResult)==TRUE)
- {
- //ConvertbstrtosomethingyoucanuseinVC++
- _bstr_tbstrDocContents=m_plDomDocument->xml;
- m_strXMLContents=(LPCTSTR)bstrDocContents;
- //getXMLdataandshowonEditControl
- MSXML2::IXMLDOMNodePtrm_pXMLRoot=m_plDomDocument->documentElement;
- //m_strXMLData=_T(",")+DisplayXMLChildren(m_pXMLRoot);
- //looptoshowgetpoint'sLonandLanandsaveinmap<CString,CString>LonLanPoints
- for(MSXML2::IXMLDOMNodePtrpChild=m_pXMLRoot->firstChild;pChild!=NULL;pChild=pChild->nextSibling)
- DisplayXMLChildren(pChild);
- }
- }
- else
- m_strXMLContents="DocumentFAILEDtoload!";
- //incaSEOfoverloaddataweusebefore,weshouldaddonebuttonforclearthedata(Readytotransfrom)
- CStringCDemoDlg::DisplayXMLChildren(MSXML2::IXMLDOMNodePtrpParent)
- //Displaycurrentnode'sname
- //everyparent'snodenameisPOINT
- CStringstrElement=((LPCTSTR)pParent->nodeName);
- //looptogetdatapChild'sparentnodeispoint,andpoint'sparentnodeisroad
- for(MSXML2::IXMLDOMNodePtrpChild=pParent->firstChild;pChild!=NULL;pChild=pChild->nextSibling)
- //strElement+=((LPCTSTR)pChild->nodeName);
- CStringnodeName=((LPCTSTR)pChild->nodeName);
- CStringLon=_T("Lon");
- CStringLan=_T("Lan");
- CStringcurrentLon,currentLan;
- if(nodeName==Lon)
- currentLon=((LPCTSTR)pChild->text);
- if(nodeName==Lan)
- currentLan=((//addonepoint'sLonandLantomap
- LonLanPoints.insert(currentLon,currentLan);
- returnstrElement;
- }
XML结构为:
- <road>
- point>
- id>/>
- Lon</Lat>
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|