现在经常会对XML文件进行操作,怎么在MFC下去读和解析XML文件呢?直接上代码:
首先得等在stdafx.h中加入这句,以引入MSXML命名空间
#import <msxml3.dll> named_guids using namespace MSXML2;
然后再要使用的类的头文件加入:
//XML Parser intellectural pointer (used in parsing XML file)
MSXML2::IXMLDOMDocument2Ptr m_plDomDocument;
MSXML2::IXMLDOMElementPtr m_pDocRoot;
然后在初始化函数中加入对XML COM的初始化:
//intianlize XML Parser COM ::CoInitialize(NULL); HRESULT hr = m_plDomDocument.CreateInstance(MSXML2::CLSID_DOMDocument); if(FAILED(hr)) { _com_error er(hr); AfxMessageBox(er.ErrorMessage()); EndDialog(1); }
接着是具体的函数:
void CDemoDlg::OnBnClickedButtonOpenxml() { // at first ,we should clear m_strXML's contents to show new data m_strXMLData = ""; CFileDialog fileDlg(TRUE); if(IDOK == fileDlg.DoModal()) { m_strXMLPath = fileDlg.GetPathName(); m_strXMLContents = "Empty document"; //just in case you don't get anything UpdateData(FALSE); //Specify XML file name CString strFileName = m_strXMLPath; //Convert XML file name string to something COM can handle _bstr_t bstrFileName; bstrFileName = strFileName.AllocSysString(); //Call the IXMLDOMDocumentPtr's load function to load XML file variant_t vResult; vResult = m_plDomDocument->load(bstrFileName); if(((bool)vResult) == TRUE ) //success { //Convert bstr to something you can use in VC++ _bstr_t bstrDocContents = m_plDomDocument->xml; m_strXMLContents = (LPCTSTR) bstrDocContents; //get XML data and show on Edit Control MSXML2::IXMLDOMNodePtr m_pXMLRoot = m_plDomDocument->documentElement; //first child is point //m_strXMLData = _T(",") + DisplayXMLChildren(m_pXMLRoot); //loop to show get point's Lon and Lan and save in map<CString,CString>LonLanPoints for(MSXML2::IXMLDOMNodePtr pChild = m_pXMLRoot->firstChild; pChild != NULL; pChild = pChild->nextSibling) { DisplayXMLChildren(pChild); } } else { m_strXMLContents = "Document FAILED to load!"; } UpdateData(FALSE); } } //in case of overload data we use before, we should add one button for clear the data(Ready to transfrom) CString CDemoDlg::DisplayXMLChildren(MSXML2::IXMLDOMNodePtr pParent) { //Display current node's name //every parent's node name is POINT CString strElement = ((LPCTSTR)pParent->nodeName); //output is point //loop to get data pChild's parent node is point,and point's parent node is road for(MSXML2::IXMLDOMNodePtr pChild = pParent->firstChild; pChild != NULL; pChild = pChild->nextSibling) { //strElement += ((LPCTSTR)pChild->nodeName); CString nodeName = ((LPCTSTR)pChild->nodeName); CString Lon = _T("Lon"); CString Lan = _T("Lan"); CString currentLon,currentLan; if ( nodeName == Lon ) { currentLon = ((LPCTSTR)pChild->text); } if ( nodeName == Lan ) { currentLan = ((LPCTSTR)pChild->text); } //add one point's Lon and Lan to map LonLanPoints.insert(currentLon,currentLan); } return strElement; }
XML结构为: <road> <point> <id><id/> <Lon></Lon> <Lat></Lat> </road>