开发环境:VS2010
一、解析xml文件:
假如已存在一个xml文件classfile.xml
#import "msxml3.dll"
using namespace MSXML2;
void CannilyxmlDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
MSXML2::IXMLDOMDocumentPtr xmldoc;
HRESULT hr;
hr = CoInitialize(NULL);//必须初始化,否则后面的CreateInstance创建文档要失败
if(FAILED (hr))//此处最好用FAILED或者SUCCEEDED来判断,否则可能引起未知错误
{
MessageBox("初始化COM失败");
}
else
{
MessageBox("初始化COM成功");
}
hr = xmldoc.CreateInstance(__uuidof(MSXML2::DOMDocument));
if(FAILED (hr))
{
MessageBox("创建xml文档对象失败");
}
else
{
MessageBox("创建xml文档对象成功");
}
xmldoc->load("classfile.xml");//此语句非常非常重要,和解析xml字符串语句只有点点区别,但引起的错误却是千差万别
MSXML2::IXMLDOMElementPtr root;
MSXML2::IXMLDOMNodeListPtr nodelist;
MSXML2::IXMLDOMNodeListPtr childnodelist;
root = xmldoc->GetdocumentElement();
nodelist = root->GetchildNodes();
MSXML2::IXMLDOMNodePtr node;
MSXML2::IXMLDOMNodePtr childnode;
for(int i=0;i<nodelist->length;i++)
{
node = nodelist->Getitem(i);
childnodelist = node->GetchildNodes();
for(int j=0;j<childnodelist->length;j++)
{
childnode = childnodelist->Getitem(i);
MessageBox(childnode->Gettext());
}
}
::CoUninitialize();
}
二、解析xml字符串
调用端:
void xmld()
{
char *info = "<?xml version = '1.0'?>
<Video>
<data>12</data>
</Video>" ;//传入一个xml形式的字符串
BSTR mation = _bstr_t(info);//将上述指针类型字符串 转化为BSTR类型
RealPlay(mation); //调用函数,传入一个字符类型参数
}
被调用端:
#import "msxml3.dll"
using namespace MSXML2;
void RealPlay(LPCTSTR msg)
{
// TODO: 在此添加控件通知处理程序代码
MSXML2::IXMLDOMDocumentPtr xmldoc;
HRESULT hr;
hr = CoInitialize(NULL);//必须初始化,否则后面的CreateInstance创建文档要失败
if(FAILED (hr))//此处最好用FAILED或者SUCCEEDED来判断,否则可能引起未知错误
{
MessageBox("初始化COM失败");
}
else
{
MessageBox("初始化COM成功");
}
hr = xmldoc.CreateInstance(__uuidof(MSXML2::DOMDocument));
if(FAILED (hr))
{
MessageBox("创建xml文档对象失败");
}
else
{
MessageBox("创建xml文档对象成功");
}
xmldoc->loadXML(msg);//此语句非常非常重要,和解析xml文件语句只有点点区别,但引起的错误却是千差万别
MSXML2::IXMLDOMElementPtr root;
MSXML2::IXMLDOMNodeListPtr nodelist;
MSXML2::IXMLDOMNodeListPtr childnodelist;
root = xmldoc->GetdocumentElement();
nodelist = root->GetchildNodes();
MSXML2::IXMLDOMNodePtr node;
MSXML2::IXMLDOMNodePtr childnode;
for(int i=0;i<nodelist->length;i++)
{
node = nodelist->Getitem(i);
childnodelist = node->GetchildNodes();
for(int j=0;j<childnodelist->length;j++)
{
childnode = childnodelist->Getitem(i);
MessageBox(childnode->Gettext());
}
}
::CoUninitialize();
}