xml例子如下:
<?xml version="1.0"?> <catalog> <book id="bk001"> <author>Eddy</author> <title>XML Developer's Guide</title> <price>16.18</price> </book> <book id="bk002"> <author>Rain</author> <title>Midnight Rain</title> <price>12.95</price> </book> <book id="bk003"> <author>Sunny</author> <title>Maeve Ascendant</title> <price>60</price> </book> </catalog>
工程首先加入msxml.tlh和msxml.tli。
然后:
#include "msxml.tlh"
新建了一个MFC简单对话框工程,代码如下:
void CtestXMLDlg::OnBnClickedOk() { //首先初始化COM HRESULT hr; hr = CoInitialize(NULL); if( hr != S_OK ) { return; } //创建Document对象 MSXML::IXMLDOMDocumentPtr pDoc; hr = pDoc.CreateInstance(__uuidof(MSXML::DOMDocument)); if( Failed(hr) ) { return; } if( FALSE == pDoc->load(_bstr_t("D:\\Book.xml")) ) { return; } //选择内容的根节点 MSXML::IXMLDOMElementPtr pElem = NULL; pElem = pDoc->selectSingleNode("catalog"); if(pElem==NULL) { return; } unsigned int nBookNum = pElem->childNodes->length; if( nBookNum == 0) { return; } for(int i=0; i < nBookNum; i++) { MSXML::IXMLDOMNodePtr pBookNode = pElem->childNodes->item[i]; if(pBookNode==NULL) { return; } //读取book节点的id属性 MSXML::IXMLDOMNodePtr pId = pBookNode->attributes->getNamedItem("id"); //读取book节点下author子节点 MSXML::IXMLDOMNodePtr pAuthorNode = pBookNode->selectSingleNode("author"); if(pAuthorNode==NULL) { ; } else { ; } } }