本文使用微软自家的MSXML解析器,请先自行安装
加入头文件
#import <msxml3.dll> named_guids using namespace MSXML2;
写入xml
::CoInitialize(NULL); //初始化组件 MSXML2::IXMLDOMDocumentPtr XMLDOC; MSXML2::IXMLDOMElementPtr XMLROOT; HRESULT HR = XMLDOC.CreateInstance(_uuidof(MSXML2::DOMDocument30)); if(!SUCCEEDED(HR)) { MessageBox(_T("faild!!")); return; } XMLROOT = XMLDOC->createElement("ROOT");//创建文件; XMLROOT->setAttribute("ID","12345"); //设置根标签的属性; XMLDOC->appendChild(XMLROOT); CString TMP; MSXML2::IXMLDOMElementPtr XMLNODE; for(int I=0;I<10;I++) { TMP.Format(_T("NODE%d"),I); XMLNODE = XMLDOC->createElement((_bstr_t)(TMP)); XMLNODE->put_text((_bstr_t)"NODETEXTS");//设置标签的文本内容; XMLNODE->setAttribute("ID",(_variant_t)TMP);//设置标签的属性及内容; XMLNODE->setAttribute("NAME","NODENAME"); XMLROOT->appendChild(XMLNODE); } XMLDOC->save("XMLTEST.XML");//保存文件; XMLROOT.Release(); XMLDOC.Release(); ::CoUninitialize();保存好的xml内容为
读取xml
::CoInitialize(NULL); MSXML2::IXMLDOMDocumentPtr XMLDOC; MSXML2::IXMLDOMElementPtr XMLROOT; MSXML2::IXMLDOMElementPtr XMLELEMENT; MSXML2::IXMLDOMNodeListPtr XMLNODES; //某个节点的所以字节点 MSXML2::IXMLDOMNamedNodeMapPtr XMLNODEATTS;//某个节点的所有属性; MSXML2::IXMLDOMNodePtr XMLNODE; HRESULT HR = XMLDOC.CreateInstance(_uuidof(MSXML2::DOMDocument30)); if(!SUCCEEDED(HR)) { MessageBox(_T("faild!!")); return; } XMLDOC->load("XMLTEST.XML"); XMLROOT = XMLDOC->GetdocumentElement();//获得根节点; XMLROOT->get_childNodes(&XMLNODES);//获得根节点的所有子节点; long XMLNODESNUM,ATTSNUM; XMLNODES->get_length(&XMLNODESNUM);//获得所有子节点的个数; CString TMP; TMP.Format(_T("%d"),XMLNODESNUM); MessageBox(TMP); for(int I=0;I<XMLNODESNUM;I++) { XMLNODES->get_item(I,&XMLNODE);//获得某个子节点; XMLNODE->get_attributes(&XMLNODEATTS);//获得某个节点的所有属性; CString temp2 = XMLNODE->Gettext(); //读取节点内容,注意与读取节点属性的顺序, MessageBox(temp2+_T("*********")); XMLNODEATTS->get_length(&ATTSNUM);//获得所有属性的个数; for(int J=0;J<ATTSNUM;J++) { XMLNODEATTS->get_item(J,&XMLNODE);//获得某个属性; CString T1 = (_bstr_t)XMLNODE->nodeName; CString T2 = (_bstr_t)XMLNODE->text; MessageBox(T1+_T(" = ")+T2); } //MessageBox((_bstr_t)XMLNODE->nodeName+": "+(_bstr_t)XMLNODE->text); CString temp3 = XMLNODE->Gettext(); //虽然此处与上面读取节点内容的代码一致,但是读取的却是节点属性的最后一个值,不知道是什么原因,求大神赐教 MessageBox(temp3+_T("++++++")); } XMLNODES.Release(); XMLNODE.Release(); XMLROOT.Release(); XMLDOC.Release(); ::CoUninitialize();原文链接:https://www.f2er.com/xml/298271.html