C++怎么运用XML文件 要自己写XML文件的解析的吗 谢谢高手回答
3个回答
展开全部
<?xml version="1.0" encoding="utf-8"?>
<Cases>
<case>
<No>001</No>
<CopyFile src="C:\test.txt" dest="D:\test.txt"></CopyFile>
</case>
<case>
<No>002</No>
<DelFile>C:\test.txt</DelFile>
</case>
</Cases>
我们用C++来读取上述xml,代码如下:
void CTestToolsDlg::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 CTestToolsDlg::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 CTestToolDlg::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();
}
CopyFile(strSrcFile, strDestFile, FALSE);
}
else if (0 == strNodeName.CompareNoCase(_T("DelFile")))
{
strDestFile.Empty();
strDestFile = CString((BSTR)strCaseNodeValue.pbstrVal);
DeleteFile(strDestFile);
}
}
}
为了能够让C++认识MSXML2,我们需要引入相应的dll,代码如下;
#import "msxml4.dll"
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询