VC简单调用MSXML

首先 安装msxml sdk

 

1、包含头文件
#include <MsXml2.h>

#include <comutil.h>
#pragma comment(lib, "comsuppw.lib")

2、例子代码
CComPtr<IXMLDOMDocument> pDoc;
HRESULT hr = pDoc.CoCreateInstance(__uuidof(DOMDocument30));
if (FAILED(hr))
{  
MessageBox(_T("无法创建DOMDocument对象!"));
return ;
}
CString strXML;
strXML = "<t publishid=\"14\" gender=\"2\" starttime=\"2011-06-22 16:50:42\" endtime=\"2011-06-30 16:50:42\" tipsshowtype=\"0\" onlineminites=\"0\" hideseconds=\"5\" url=\"http://192.168.10.93:8080/dodonew/front/resource/hometemplate/showtips3.htm?publishId=14\" />";
VARIANT_BOOL bRet = VARIANT_FALSE;
//加载文件或XML文本
//pDoc->load()
pDoc->loadXML(strXML.AllocSysString(), &bRet);
if (!bRet)
{
return;
}
CString strNode(_T("//t"));
IXMLDOMNode* pNode = NULL;
pDoc->selectSingleNode(strNode.AllocSysString(), &pNode);
long count = 0;
//节点属性,放在链表中
IXMLDOMNamedNodeMap* pAttrMap = NULL;
pNode->get_attributes(&pAttrMap);
pAttrMap->get_length(&count);
for (long i = 0; i < count; i++)
{
IXMLDOMNode* pAttrItem = NULL;
pAttrMap->get_item(i, &pAttrItem);
//取得节点的值
_variant_t variantValue;
pAttrItem->get_nodeTypedValue(&variantValue);
_bstr_t bstrValue = variantValue;
CString strValue = bstrValue;
TRACE("%s\n", strValue);
}
//子节点, 放在链表中
IXMLDOMNodeList* pNodeList = NULL;
pNode->get_childNodes(&pNodeList);
pNodeList->get_length(&count);
for (long i = 0; i < count; i++)
{
IXMLDOMNode* pChildNode = NULL;
pNodeList->get_item(i, &pChildNode);
_variant_t variantValue;
pChildNode->get_nodeTypedValue(&variantValue);
_bstr_t bstrValue = variantValue;
CString strValue = bstrValue;
TRACE("%s\n", strValue);
}
 
 
//读取指定xml文件

 CComPtr<IXMLDOMDocument> pDoc;
 HRESULT hr = pDoc.CoCreateInstance(__uuidof(DOMDocument30));
 if (FAILED(hr))
 { 
  AfxMessageBox(_T("无法创建DOMDocument对象!"));
  return ;
 }
    CString filePath;
 
 VARIANT_BOOL bRet = VARIANT_FALSE;

 CString filePath;
 GetModuleFileName(_hdllInstance,filePath.GetBuffer(0),MAX_PATH);  
 filePath.ReleaseBuffer();
  filePath=filePath.Mid(0,filePath.ReverseFind(_T('\\')))+_T("\\a.xml");
    _variant_t vt(filePath);

 pDoc->load(vt,&bRet);
    if (bRet)
    {
 
    IXMLDOMNode* pNode = NULL;
    IXMLDOMElement *el=NULL;
    pDoc->get_documentElement(&el);
    BSTR tmp;
    el->get_baseName(&tmp);
    CString bName(tmp);
    IXMLDOMNodeList *nl=NULL;
    CString strNode(_T("./*")); //获取当前节点的所有1级子节点
    el->selectNodes(strNode.AllocSysString(),&nl);
    long l;
    nl->get_length(&l);  
        
   }

 
 
 

你可能感兴趣的:(VC简单调用MSXML)