MFC怎么读取XML文件
2018-01-06 · 知道合伙人数码行家
知道合伙人数码行家
向TA提问 私信TA
void CXXXDlg::ReadXml(CString strXmlPath)
{
MSXML2::IXMLDOMDocumentPtr pDoc;
::CoInitialize(NULL);
HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument40));
if (!SUCCEEDED(hr))
{
MessageBox(_T("创建DOMDocument对象失败。\n请检查运行环境"), _T("错误"), MB_ICONERROR);
return;
} // 读取xml
pDoc->put_async(VARIANT_FALSE);
VARIANT_BOOL bhr = pDoc->load((_variant_t)strXmlPath); if (bhr != VARIANT_TRUE) {
MessageBox(_T("无法正确读取xml文件"), _T("错误"), MB_ICONERROR); return;
}
// 根节点取得
MSXML2::IXMLDOMElementPtr root = pDoc->documentElement; // 取得根节点的名字
_variant_t strRootName = root->nodeName;
_bstr_t wstrRootName(strRootName.bstrVal);
MSXML2::IXMLDOMNodeListPtr nodeList = root->GetchildNodes();//cases
// 解析cases的子节点
ReadCases(nodeList);
}
void CXXXDlg::ReadCases(MSXML2::IXMLDOMNodeListPtr nodeList)
{ int ilength = nodeList->Getlength(); for (int nodeCount = 0; nodeCount < ilength; nodeCount++) {
MSXML2::IXMLDOMNodePtr nodePtr = nodeList->nextNode();
_variant_t strNodeName = nodePtr->GetnodeName();
_variant_t strNodeValue = nodePtr->GetnodeValue();
// 读取case节点下的子节点
ReadCase(nodePtr->GetchildNodes());
}
}void CXXXDlg::ReadCase(MSXML2::IXMLDOMNodeListPtr nodeList)
{
CString strLogInfo;
strLogInfo.Empty();
CString strNo; // case编号
CString strSrcFile; // 源文件
CString strDestFile; // 目标文件
for (int nodeCount = 0; nodeCount < nodeList->Getlength(); nodeCount++)
{
MSXML2::IXMLDOMNodePtr nodePtr = nodeList->nextNode();
_variant_t strCaseNodeName = nodePtr->GetnodeName();
_variant_t strCaseNodeValue = nodePtr->Gettext();
BSTR bStrTemp = strCaseNodeName.bstrVal;
CString strTemp = CString(bStrTemp);
SysFreeString(bStrTemp);
CString strNodeName = strTemp; // 节点的值,如何取得?
if (0 == strNodeName.CompareNoCase(_T("NO")))
{
strNo = (BSTR)strCaseNodeValue.pbstrVal;
// 取得的值可以打印出来 printf(strNo);
}
// 节点有属性值,该怎么处理?
else if (0 == strNodeName.CompareNoCase(_T("CopyFile")))
{
strSrcFile.Empty();
strDestFile.Empty(); // 取得节点的属性值
MSXML2::IXMLDOMNamedNodeMapPtr pDOMAttrList= nodePtr->Getattributes(); for (int j = 0; j < pDOMAttrList->Getlength(); j++)
{
MSXML2::IXMLDOMNodePtr pDOMAttr= pDOMAttrList->Getitem(j);
// 取得源文件路径
if (CompareNoCase((char*)pDOMAttr->GetnodeName(), _T("src")))
{
strSrcFile = pDOMAttr->GetnodeTypedValue(); // 取得目标文件路径
} else if (CompareNoCase((char*)pDOMAttr->GetnodeName(), _T("dest")))
{
strDestFile =pDOMAttr->GetnodeTypedValue();
}
printf("strSrcFile = %s\n", strSrcFile);
printf("strDestFile = %s\n", strDestFile );
} else if (0 == strNodeName.CompareNoCase(_T("DelFile")))
{
strDestFile.Empty();
strDestFile = CString((BSTR)strCaseNodeValue.pbstrVal);
printf("strDestFile = %s\n", strDestFile );
}
}
}
为了能够让MFC认识MSXML2,我们需要引入相应的dll,代码如下;
#import "msxml4.dll"