程序是win32控制台程序
// msxml.cpp : 定义控制台应用程序的入口点。#include "stdafx.h"#include#include #import using namespace MSXML2;using namespace std;void msxml2_init(){ ::CoInitialize(NULL);}void msxml2_del(){ ::CoUninitialize();}/* nodename: 要查找的节点的名字* xmbuf: xml字符串* 函数功能:查找目标节点的所有属性值*/void find_node_attr(char *nodename, char *xmlbuf){ MSXML2::IXMLDOMDocumentPtr pDoc; HRESULT hr; hr=pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60)); if(FAILED(hr)) { printf("无法创建DOMDocument对象,请检查是否安装了MS XML Parser 运行库!\n"); return ; } /* 加载xml字符串 */ pDoc->loadXML(xmlbuf); MSXML2::IXMLDOMNodePtr pRoot_node, pNode; MSXML2::IXMLDOMNamedNodeMapPtr pAttrs; MSXML2::IXMLDOMNodePtr pAttrItem; long nCount; /* 在树中查找名为Book的节点,"//"表示在任意一层查找 */ char tmpnodename[20] = "//"; strncat(tmpnodename, nodename, 3); pNode = pDoc->selectSingleNode(tmpnodename); /* get_attributes()来获取该节点的所有属性列表 */ pNode->get_attributes(&pAttrs); pAttrs->get_length(&nCount); cout << "共有" << nCount << "个属性值" << nCount << endl; for(int i = 0 ; i < nCount ; i++) { pAttrs->get_item(i, &pAttrItem); /* nodeName, nodeTypedValue得到属性名和属性值 */ cout << (_bstr_t)pAttrItem->nodeName << ":" ; cout << (_bstr_t)pAttrItem->nodeTypedValue << endl; } //使用过了的指针要释放。未使用的指针不要释放,否则会触发中断错误。 pDoc.Release(); pNode.Release(); pAttrs.Release(); pAttrItem.Release();}/* * 函数功能:遍历整个xml_buf的内容并打印节点名字和节点的属性值 */void print_xmlnode(char *xmlbuf){ MSXML2::IXMLDOMDocumentPtr pDoc; HRESULT hr; hr=pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60)); if(FAILED(hr)) { printf("无法创建DOMDocument对象,请检查是否安装了MS XML Parser 运行库!\n"); return ; } /* 加载xml字符串 */ pDoc->loadXML(xmlbuf); MSXML2::IXMLDOMNodePtr pGwsIp_node, pRoot_node, pNode; MSXML2::IXMLDOMNamedNodeMapPtr pAttrs = NULL; MSXML2::IXMLDOMNodePtr pAttrItem; /* 遍历整个xml_buf的内容并打印节点名字和节点的属性值 */ pRoot_node = pDoc->firstChild; pGwsIp_node = pRoot_node->firstChild;//pDoc->firstChild->firstChild; MSXML2::DOMNodeType nodeType; long nCount ; //节点名称 root下子节点的个数 unsigned int num = pRoot_node->childNodes->length; cout << "num = " << num << endl; char node_name[20] = {}; //Gettext()获取节点值 for(int i = 0; i < num; i++) { strcpy(node_name, pRoot_node->childNodes->item[i]->Gettext()); cout << "node_name = " << node_name << endl; } /*IXMLDOMNamedNodeMap是xml中描述一个结点属性的接口, 通过它用户可以对某个节点的属性进行操作*/ pGwsIp_node->get_attributes(&pAttrs); pAttrs->get_length(&nCount); for(int i = 0 ; i < nCount ; i++) { pAttrs->get_item(i,&pAttrItem); /*get_nodeName,get_nodeTypedValue得到属性名和属性值*/ cout << (_bstr_t)pAttrItem->nodeName << ":" ; cout << (_bstr_t)pAttrItem->nodeTypedValue << endl; } //使用过了的指针要释放。未使用的指针不要释放,否则会触发中断错误。 pDoc.Release(); pRoot_node.Release(); pGwsIp_node.Release(); pAttrs.Release(); pAttrItem.Release();}int _tmain(int argc, _TCHAR* argv[]){ msxml2_init(); char buf[300] = " "; find_node_attr("gws", buf); print_xmlnode(buf); getchar(); msxml2_del(); return 0;} 一个节点 二个节点
运行后的效果