如何在VC环境下编写程序读取XML文件?

#import <msxml3.dll> named_guids  //导入动态库,装了IE5就有
using namespace MSXML2;     //引用命名空间,一般可以把命名空间理解成类和接口的集合,呵呵,对不对我也不知道了
#include <vector>
using namespace std;
struct FIELD
{
public:
 CString  name;
 CString  type;
 CString  length;
 CString  explain;
 CString  allowNull;
 CString  autoIncrease;
};
class Xml
{
public:
 Xml(void);
 ~Xml(void);
private:
 HRESULT hr;
 MSXML2::IXMLDOMDocumentPtr pDoc; //XML文档接口指针
public:
 void AddKey(CString moduleName,CString keyName, CString keyValue);
 CString ReadKeyValue(CString moduleName, CString keyName);
private:
 void NewDocument(CString moduleName, CString keyName, CString keyValue);
public:
 bool ReadTable(CTreeCtrl * tree);
 bool ReadFields(CString tableName,vector<FIELD> &fields);
 bool SaveTable(vector<FIELD> fields,CString tableName,bool bNew);
};

//-------------------------------------------------------------------------------------------------------------------------------------

上面是头文件,这是cpp文件

#include "StdAfx.h"
#include "xml.h"

Xml::Xml(void)
{

 CoInitialize(NULL);                       //初始化COM
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMDocument,(void**)&pDoc); //创建XML文档实例
}

Xml::~Xml(void)
{
 CoUninitialize();
}

void Xml::AddKey(CString moduleName,CString keyName, CString keyValue)
{
 CString selectString="AppSetting/"+moduleName;                //XML节点定位字符串,定位到节点名为moduleName的二级节点,根节点取默认名为"AppSetting"
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMDocument,(void**)&pDoc); //创建文档实例
 CFileFind finder;                       //查找文件是否存在的MFC类
 if(!finder.FindFile("Config.xml"))                   //查找文件是否存在,不存在则调用函数生成一个新的XML文件
 {
  NewDocument(moduleName,keyName,keyValue);
  return;
 }
 pDoc->load("Config.xml");                     //从应用程序目录中加载XML文件
 MSXML2::IXMLDOMNodePtr moduleNode;                   //XML节点接口指针
 MSXML2::IXMLDOMNodePtr keyNode;                    //同上
 MSXML2::IXMLDOMNodePtr selectNode;                   //同上
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMNode,(void**)&moduleNode); //创建节点实例
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMNode,(void**)&keyNode); //同上
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMNode,(void**)&selectNode); //同上
 moduleNode=pDoc->selectSingleNode((_bstr_t)selectString);             //定位到节点名为moduleName的二级节点
 if(moduleNode==NULL)                      //如果无法定位,说明还不存在此节点,生成一个新的节点
 {
  selectNode=pDoc->selectSingleNode("AppSetting");              //定位到根节点,这里一定能定位成功,除非手动改了XML文件
  moduleNode=pDoc->createNode(1,(_bstr_t)moduleName,"");             //生成新节点
        selectNode->appendChild(moduleNode);                 //将新节点添加到根节点
 }
 selectString+="/"+keyName;                     //XML节点定位字符串,定位到节点名为keyName的三级节点
 keyNode=pDoc->selectSingleNode((_bstr_t)selectString);              //定位到节点名为keyName的三级节点
 if(keyNode==NULL)                       //如果无法定位,说明还不存在此节点,生成一个新的节点
 {
  keyNode=pDoc->createNode(1,(_bstr_t)keyName,"");              //生成新节点
  moduleNode->appendChild(keyNode);                  //将新节点添加到节点名moduleName的节点
 }
 keyNode->text=(_bstr_t)keyValue;                   //给节点名为keyName的节点赋text值秋keyValue
 pDoc->save("Config.xml");                     //保存
}

CString Xml::ReadKeyValue(CString moduleName, CString keyName)
{
 CString selectString="AppSetting/"+moduleName+"/"+keyName;
 CString keyValue="";
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMDocument,(void**)&pDoc); //创建文档实例
 CFileFind finder;                       //查找文件是否存在的MFC类
 if(!finder.FindFile("Config.xml"))                   //查找文件是否存在,不存在则调用函数生成一个新的XML文件
 {
  return "";
 }
 pDoc->load("Config.xml");
 MSXML2::IXMLDOMNodePtr selectNode;                   //同上
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMNode,(void**)&selectNode); //创建节点实例
 selectNode=pDoc->selectSingleNode((_bstr_t)selectString);
 if(selectNode==NULL)
 {
  return "";
 }
 else
 {
  return (CString)((BSTR)selectNode->text);
 }
}

void Xml::NewDocument(CString moduleName, CString keyName, CString keyValue)
{
 CString strXml="<AppSetting><"+moduleName+"><"+keyName+">"+keyValue+"</"+keyName+"></"+moduleName+"></AppSetting>"; //XML字符串
 pDoc->loadXML((_bstr_t)strXml);                      //通过加载字符生成XML的Document,此处用方法loadXml,从文件加载用load,参考前面
 pDoc->save("Config.xml");                       //保存
}


bool Xml::ReadTable(CTreeCtrl * tree)
{
 CString selectString="DataResource/Tables/Table";
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMDocument,(void**)&pDoc); //创建文档实例
 CFileFind finder;                       //查找文件是否存在的MFC类
 if(!finder.FindFile("DataResource.xml"))                 //查找文件是否存在,不存在则调用函数生成一个新的XML文件
 {
  return false;
 }
 pDoc->load("DataResource.xml");
 MSXML2::IXMLDOMElementPtr node;                     //同上
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMElement,(void**)&node);  //创建节点实例
 MSXML2::IXMLDOMNodeListPtr selectNodes;                    
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMNodeList,(void**)&selectNodes);//创建节点列表实例
 selectNodes=pDoc->selectNodes((_bstr_t)selectString);               //查找节点集
 
 HTREEITEM tabItem=tree->GetChildItem(tree->GetRootItem());
 if(selectNodes==NULL)
 {
  return false;
 }
 else
 {
  for(long i=0;i<selectNodes->Getlength();i++)
  {
   
   node=selectNodes->Getitem(i);
   _variant_t nodeName=node->getAttribute("Name");
   
   tree->InsertItem((CString)nodeName.bstrVal,3,3,tabItem);
  }
  
  //return (CString)((BSTR)selectNode->text);
 }
 return true;
}
bool Xml::ReadFields(CString tableName,vector<FIELD> &fields)
{
 
 CString selectString="DataResource/Tables/Table";
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMDocument,(void**)&pDoc); //创建文档实例
 CFileFind finder;                       //查找文件是否存在的MFC类
 if(!finder.FindFile("DataResource.xml"))                 //查找文件是否存在,不存在则调用函数生成一个新的XML文件
 {
  return false;
 }
 pDoc->load("DataResource.xml");
 MSXML2::IXMLDOMElementPtr node;                     //同上
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMElement,(void**)&node);  //创建节点实例
 MSXML2::IXMLDOMNodeListPtr tableNodes;                    
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMNodeList,(void**)&tableNodes);//创建节点列表实例
 MSXML2::IXMLDOMNodeListPtr fieldNodes;                    
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMNodeList,(void**)&fieldNodes);//创建节点列表实例
 tableNodes=pDoc->selectNodes((_bstr_t)selectString);               //查找节点集
 
 if(tableNodes==NULL)
 {
  return false;
 }
 for(long i=0;i<tableNodes->Getlength();i++)
 {
  node=tableNodes->Getitem(i);
  CString nodeName=(CString)node->getAttribute("Name");
  if(nodeName==tableName)
  {
   fieldNodes=node->GetchildNodes();
   break;
  }
 }
 if(fieldNodes==NULL)
 {
  return false;
 }
 fields.clear();
 for(long i=0;i<fieldNodes->Getlength();i++)
 {
  FIELD field;
  node=fieldNodes->Getitem(i);
  field.autoIncrease=node->getAttribute("AutoIncrease");
  field.explain=node->getAttribute("Explain");
  field.length=node->getAttribute("Length");
  field.name=node->getAttribute("Name");
  field.type=node->getAttribute("Type");
  field.allowNull=node->getAttribute("AllowNull");
  fields.push_back(field);
  
 }
 return true;
}
bool Xml::SaveTable(vector<FIELD> fields,CString tableName,bool bNew)
{
 
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMDocument,(void**)&pDoc);   //创建文档实例
 CFileFind finder;                         //查找文件是否存在的MFC类
 if(!finder.FindFile("DataResource.xml"))                   //查找文件是否存在,不存在则调用函数生成一个新的XML文件
 {
  return false;
 }
 pDoc->load("DataResource.xml");
 CString selectString="";
 selectString="DataResource/Tables";
 MSXML2::IXMLDOMNodePtr tablesNode;
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMNode,(void**)&tablesNode);   //创建节点实例
 MSXML2::IXMLDOMElementPtr tableNode;                    //同上
 hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMElement,(void**)&tableNode);  //创建节点实例
 tablesNode=pDoc->selectSingleNode((_bstr_t)selectString);               //查找节点集
 if(bNew)
 {
  tableNode=pDoc->createNode(1,"Table","");
  tableNode->setAttribute("Name",(_bstr_t)tableName);
 }
 else
 {
  MSXML2::IXMLDOMNodeListPtr tableNodeList;                    
  hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMNodeList,(void**)&tableNodeList);  //创建节点列表实例
  tableNodeList=tablesNode->GetchildNodes();
  CString nodeName="";
  for(int i=0;i<tableNodeList->Getlength();i++)
  {
   tableNode=tableNodeList->Getitem(i);
   nodeName=tableNode->getAttribute("Name");
   if(nodeName.MakeLower()==tableName.MakeLower())
   {
    MSXML2::IXMLDOMElementPtr fieldNode;                   //同上
    hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMElement,(void**)&fieldNode);   //创建节点实例
    int fieldsCount=tableNode->GetchildNodes()->Getlength();
    for(int j=fieldsCount-1;j>-1;j--)
    {
     fieldNode=tableNode->GetchildNodes()->Getitem(j);
     tableNode->removeChild(fieldNode);
    }
    break;
   }
   if(i==tableNodeList->Getlength())
   {
    return false;
   }
  }
 }
 for(int i=0;i<fields.size();i++)
 {
  MSXML2::IXMLDOMElementPtr fieldNode;                   //同上
  hr=CoCreateInstance(MSXML2::CLSID_DOMDocument,NULL,CLSCTX_ALL,MSXML2::IID_IXMLDOMElement,(void**)&fieldNode); //创建节点实例
  fieldNode=pDoc->createNode(1,"Field","");
  FIELD field=fields[i];
  fieldNode->setAttribute("Name",(_bstr_t)field.name);
  fieldNode->setAttribute((_bstr_t)"AllowNull",(_bstr_t)field.allowNull);
  fieldNode->setAttribute((_bstr_t)"AutoIncrease",(_bstr_t)field.autoIncrease);
  fieldNode->setAttribute((_bstr_t)"Explain",(_bstr_t)field.explain);
  fieldNode->setAttribute((_bstr_t)"Length",(_bstr_t)field.length);
  fieldNode->setAttribute((_bstr_t)"Type",(_bstr_t)field.type);
  tableNode->appendChild(fieldNode);
 }
 if(bNew)
  tablesNode->appendChild(tableNode);
 pDoc->save("DataResource.xml");
 return true;
}







//下面是另外的一段代码
{
 // TODO: Add your implementation code here
 CComPtr<xml::IXMLDOMDocument> pDoc;

 try
 {
  HRESULT hr = pDoc.CoCreateInstance(L"Msxml2.DOMDocument.4.0");
  if (FAILED(hr)) return hr;

  CComPtr<xml::IXMLDOMElement> pRoot;
  hr = pDoc->get_documentElement(&pRoot);
  if (FAILED(hr)) return hr;

  //create comment
  CComPtr<xml::IXMLDOMComment> pComm;
  hr=pDoc->createComment(CComBSTR(L"Compupacific Entry Template"),&pComm);
  if (FAILED(hr)) return hr;
  hr=pDoc->appendChild(pComm,0);

  //Root of the Doc
  CComPtr<xml::IXMLDOMElement> pElem;
  hr = pDoc->createElement(CComBSTR(L"Template"), &pElem);
  if (FAILED(hr)) return hr;

  hr = pDoc->putref_documentElement(pElem);
  if (FAILED(hr)) return hr;
  
  VARIANT var;
  var.vt=VT_BSTR;
  var.bstrVal=::SysAllocString(m_bstrCaption);
  hr = pElem->setAttribute(CComBSTR(L"Name"), var);
  ::SysFreeString(var.bstrVal);
  if (FAILED(hr)) return hr;
 
  VARIANT var1;
  var1.vt=VT_BSTR;
  var1.bstrVal=::SysAllocString(m_bstrSampleImage);
  hr = pElem->setAttribute(CComBSTR(L"Sample"), var1);
  ::SysFreeString(var1.bstrVal);
  if (FAILED(hr)) return hr;

  VARIANT var2;
  var2.vt=VT_I2;
  var2.iVal=m_shDock;
  hr = pElem->setAttribute(CComBSTR(L"Dock"), var2);
  if (FAILED(hr)) return hr;
 }
 catch(...)
 {
  ::MessageBox(NULL,_T("Error in save form property!"),_T("Error Report"),MB_OK);
  return S_FALSE;
 }
 try
 {
  //Now tell the form to persist its child controls
  CComBSTR Tmp;
  for(std::list<CAxWindowHandle* >::iterator it = m_listSites.begin(); it != m_listSites.end();it++)
  { 
   if(*it)
   {
    CComPtr<xml::IXMLDOMElement> pRoot;
    HRESULT hr = pDoc->get_documentElement(&pRoot);
    if (FAILED(hr)) return hr;
    
    CComPtr<xml::IXMLDOMNode> pNode;
    Tmp=OLESTR("Control");
    CComBSTR Tmp1;
    hr = pDoc->createNode(CComVariant(1),Tmp.m_str, Tmp1.m_str, &pNode);
    if (FAILED(hr)) return hr;
       
    hr = pRoot->appendChild(pNode.p, 0);
    if (FAILED(hr)) return hr;

    CComPtr<IPersistPropertyBag> spPersistPropBag;
    hr = (*it)->QueryControl(&spPersistPropBag);
    if (FAILED(hr)) return hr;
    
    hr = spPersistPropBag->InitNew();
    if (FAILED(hr)) return hr;

    CComPtr<IPersistPropertyBag> spExtendedPPB;
    if((*it)->m_pExtendedDispatchObj)
    {
     hr = (*it)->m_pExtendedDispatchObj->QueryInterface(&spExtendedPPB);
     if (FAILED(hr)) return hr;
    }
    
    CComQIPtr<xml::IXMLDOMElement> pElem(pNode);
    if(!pElem) return E_NOINTERFACE;
    
    //Save Extended Properties
    hr = SaveToXML(pDoc, pElem.p, spExtendedPPB, TRUE, TRUE);
    if (FAILED(hr)) return hr;

    //Save Native Properties
    hr = SaveToXML(pDoc, pElem.p, spPersistPropBag, TRUE, TRUE);
    if (FAILED(hr)) return hr;
   }
  }
   
  return pDoc->save(CComVariant(FileName));    
 }
 catch(...)
 {
  ::MessageBox(NULL,_T("Error in save control property!"),_T("Error Report"),MB_OK);
  return S_FALSE;
 }
}

posted on 2010-10-15 13:34 wrh 阅读(2368) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
【推荐】超50万行VC++源码: 大型组态工控、电力仿真CAD与GIS源码库
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2010年7月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

统计

常用链接

留言簿(18)

随笔档案

文章档案

收藏夹

搜索

最新评论

阅读排行榜

评论排行榜