VC++中XML文件的解析读取写入

1、在stdafx.h中引用如下
#include "TLH/msxml4.tlh" using namespace MSXML2
2、在app文件中注意初始化com
#if _WIN32_WINNT >= 0x0400
 HRESULT hRes = CoInitializeEx(NULL, COINIT_MULTITHREADED);
#else
 HRESULT hRes = CoInitialize(NULL);
#endif
注意在ExitInstance函数中写在初始化的com
CoUninitialize();

3、定义document变量
MSXML2::IXMLDOMDocumentPtr m_pXMLDoc;


//读取XML信息
bool ReadXML(CString strPath)
{
 bool bRgs = false;
 try
 {  
  if (strPath.IsEmpty()) 
   return false;
  _bstr_t strURL(strPath);         
  HRESULT hr = m_pXMLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument));
    m_pXMLDoc->async = VARIANT_FALSE; // default - true,
  m_pXMLDoc->validateOnParse = VARIANT_FALSE;
  hr = m_pXMLDoc->load(strURL);
  if(hr!=VARIANT_TRUE)
  {
   MSXML2::IXMLDOMParseErrorPtr  pError;
   pError = m_pXMLDoc->parseError;
   _bstr_t parseError =_bstr_t("At line ")+ _bstr_t(pError->Getline()) + _bstr_t("/n")+ _bstr_t(pError->Getreason());
   ::MessageBox(NULL,parseError, "Parse Error",MB_OK);
   bRgs = false;  
  }
  else
   bRgs = true;  
 }
 catch(_com_error &e)
 {
  _bstr_t bt = e.Description();
  ::MessageBox(NULL,bt,"Catch Error",MB_OK);
 }
 return bRgs;
} 

//读取xml文件的节点值:
//xmleg.
//
//
//name="admin",birthday="1928-1-2",sex="male",addr="Hongkong"
//
CString GetNodeContent(_bstr_t bstrName)//bstrName="/config/childnode1"
{
CString strRgs(_T(""));
 try
 {
  
  MSXML2::IXMLDOMNodePtr pNode = m_pXMLDoc->selectSingleNode(bstrName);
  _bstr_t bt = pNode->Gettext();
  strRgs = bt.copy();
  
 }
 catch(...)
 {
 }
 return strRgs;
}

//读取xml文件的属性值:
//xml 文件
//eg.
//
//
//
//
//方法一:
CString GetNodeAttributes(_bstr_t bstrName,CStringArray& arrAttributeName,CStringArray& arrAttributeValue)//bstrName="/config/childnode1"
{
 arrAttribute.RemoveAll();
 try
 {
  
  MSXML2::IXMLDOMNodePtr pNode = m_pXMLDoc->selectSingleNode(bstrName);
  MSXML2::IXMLDOMNamedNodeMapPtr nameattr = pNode->Getattributes();
  
  int iLength = nameattr->Getlength();
  for (int j = 0; jGetitem(j);
   MSXML2::DOMNodeType pNodeType = pNode->GetnodeType();
   if (pNodeType == NODE_ELEMENT) 
   {
    CString strTmp;
    _bstr_t kt ;
    kt = pN->GetnodeName();
    strTmp = kt.copy();
    arrAttributeName.Add(strTmp);
    kt = pN->Gettext();
    CString strTmp = kt.copy();
    arrAttribute.Add(strTmp);
   }
  }
 }
 catch(...)
 {
 }
 return strRgs;
}
//方法二
CString GetNodeAttributes(_bstr_t bstrName)//bstrName="/config/childnode1"
{
 arrAttribute.RemoveAll();
 try
 {
  
  MSXML2::IXMLDOMNodePtr pNode = m_pXMLDoc->selectSingleNode(bstrName);
  MSXML2::IXMLDOMElementPtr pElement = pNode;
  _variant_t vt;
  vt = pElement->getAttribute(_bstr_t("name"));
  vt = pElement->getAttribute(_bstr_t("birthday"));
  vt = pElement->getAttribute(_bstr_t("sex"));
  vt = pElement->getAttribute(_bstr_t("addr"));
 }
 catch(...)
 {
 }
}

你可能感兴趣的:(程序,VC++)