调用微软msxml解析xml文档
XML数据格式如下:
test.xml
<?xml version="1.0" encoding="gb2312"?>
<Top Attr="Top">
<Mid Attr="Mid">
<Leaf Attr="Leaf"/>
</Mid>
</Top>
用vs2005写一个win32的控制台程序。
文件如下:
// XmlSupport.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "XmlSupport.h"
#include <msxml2.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// The one and only application object
CWinApp theApp;
using namespace std;
#ifdef UNICODE
#define MYOUT wcout
#else
#define MYOUT cout
#endif
bool LoadFile(IXMLDOMDocument* pXmlDom);
CString GetNodeAttr(IXMLDOMNode* pCurNode, const CString& strAttr);
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
return nRetCode;
}
//支持com组件
CoInitialize(NULL);
CComPtr<IXMLDOMDocument> m_spXMLDOM;
HRESULT hrCreate = m_spXMLDOM.CoCreateInstance(__uuidof(DOMDocument40));
if (FAILED(hrCreate) || m_spXMLDOM.p == NULL)
{
return 0;
}
if (!LoadFile(m_spXMLDOM))
{
return 0;
}
CComPtr<IXMLDOMNode> pTopNode;
m_spXMLDOM->selectSingleNode(_T("Top"),&pTopNode);
CString strTopValue = GetNodeAttr(pTopNode, _T("Attr"));
MYOUT<<strTopValue.GetBuffer()<<endl;
strTopValue.ReleaseBuffer();
CComPtr<IXMLDOMNode> pMidNode;
pTopNode->selectSingleNode(_T("Mid"), &pMidNode);
CString strMidValue = GetNodeAttr(pMidNode, _T("Attr"));
MYOUT<<strMidValue.GetBuffer()<<endl;
strMidValue.ReleaseBuffer();
CComPtr<IXMLDOMNode> pLeafNode;
pMidNode->selectSingleNode(_T("Leaf"), &pLeafNode);
CString strLeafValue = GetNodeAttr(pLeafNode, _T("Attr"));
MYOUT<<strLeafValue.GetBuffer()<<endl;
strLeafValue.ReleaseBuffer();
pLeafNode.Release();
pMidNode.Release();
pTopNode.Release();
m_spXMLDOM.Release();
CoUninitialize();
return nRetCode;
}
bool LoadFile(IXMLDOMDocument* pXmlDom)
{
CComBSTR strXmlFile = _T("d:\\test.xml");
VARIANT va;
va.vt=VT_BSTR;///指明整型数据
va.bstrVal=strXmlFile; ///赋值
VARIANT_BOOL bSuccess = false;
HRESULT hr = pXmlDom->load(va, &bSuccess);
if( FAILED(hr) || !bSuccess)
{
return false;
}
return true;
}
CString GetNodeAttr(IXMLDOMNode* pCurNode, const CString& strAttr)
{
CComBSTR an(strAttr);
CString strValue = _T("");
IXMLDOMNamedNodeMap* pIXMLDOMNamedNodeMap=NULL;
HRESULT hrAttr = pCurNode->get_attributes(&pIXMLDOMNamedNodeMap);
if (SUCCEEDED(hrAttr) && pIXMLDOMNamedNodeMap)
{
IXMLDOMNode * pIXMLDOMNode=NULL;
hrAttr = pIXMLDOMNamedNodeMap->getQualifiedItem(an, NULL, &pIXMLDOMNode);
if (SUCCEEDED(hrAttr) && pIXMLDOMNode)
{
CComVariant varValue(VT_EMPTY);
pIXMLDOMNode->get_nodeValue(&varValue);
strValue = varValue;
}
}
pIXMLDOMNamedNodeMap->Release();
return strValue;
}