XML最近被吹的神乎其神,很多数据的交换,包括很多中间件系统,WebService,软件的配置文件,都是在用XML这个技术,的确是个好东西,下面写了个读取XML的代码片段,用的是MSXML的一些接口。
读的是BT软件的配置文件,XML内容如下:
<?xml version="1.0"?>
<BitComet Author="RnySmile" Version="0.1">
<Settings>
<LastSaveLocation>E:\电子书</LastSaveLocation>
<ListenPort>8497</ListenPort>
<GlobalMaxUploadRate>3072</GlobalMaxUploadRate>
<LastAdCacheClearDate>13104</LastAdCacheClearDate>
<LastTrackerKey>16547</LastTrackerKey>
<TotalUpload>303008</TotalUpload>
<TotalDownload>1180107</TotalDownload>
<LastExitTime>1132203124</LastExitTime>
</Settings>
</BitComet>
代码如下:
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <msxml.h>
#include <atlstr.h>
#import "msxml.dll" raw_interfaces_only
int _tmain(int argc, _TCHAR* argv[])
{
::CoInitialize(NULL);
CComPtr<MSXML::IXMLDOMDocument> spDoc;
HRESULT hr = spDoc.CoCreateInstance(__uuidof(MSXML::DOMDocument)); //创建文档对象
VARIANT_BOOL bFlag;
hr = spDoc->load(CComVariant(L"BitComet.xml"), &bFlag); //load xml文件
CComPtr<MSXML::IXMLDOMElement> spElement;
hr = spDoc->get_documentElement(&spElement); //获取根结点
CComBSTR strTagName;
hr = spElement->get_tagName(&strTagName);
cout << "------TagName------" << endl;
cout << CString(strTagName) << endl;
CComPtr<MSXML::IXMLDOMNodeList> spNodeList;
hr = spElement->get_childNodes(&spNodeList); //获取子结点列表
long lCount;
hr = spNodeList->get_length(&lCount);
for (long i=0; i<lCount; ++i)
{
CComVariant varNodeValue;
CComPtr<MSXML::IXMLDOMNode> spNode;
MSXML::DOMNodeType NodeType;
CComPtr<MSXML::IXMLDOMNodeList> spChildNodeList;
hr = spNodeList->get_item(i, &spNode); //获取结点
hr = spNode->get_nodeType(&NodeType); //获取结点信息的类型
if (NODE_ELEMENT == NodeType)
{
hr = spNode->get_childNodes(&spChildNodeList);
long childLen;
hr = spChildNodeList->get_length(&childLen);
cout << "------NodeList------" << endl;
for (int j=0; j<childLen; ++j)
{
CComPtr<MSXML::IXMLDOMNode> spChildNode;
CComBSTR value;
hr = spChildNodeList->get_item(j, &spChildNode);
hr = spChildNode->get_nodeName(&value); //获取结点名字
cout << CString(value) << endl;
hr = spChildNode->get_text(&value); //获取结点的值
cout << CString(value) << endl << endl;
spChildNode.Release();
}
}
spNode.Release();
spChildNodeList.Release();
}
spNodeList.Release();
spElement.Release();
spDoc.Release();
::CoUninitialize();
return 0;
}
输出结果如下:
------TagName------
BitComet
------NodeList------
LastSaveLocation
E:\电子书
ListenPort
8497
GlobalMaxUploadRate
3072
LastAdCacheClearDate
13104
LastTrackerKey
16547
TotalUpload
303008
TotalDownload
1180107
LastExitTime
1132203124
这是一个最简单的demo,下次软件的配置信息,可以考虑用XML